Create variable to JavaScript array from another function? - javascript

I have a function that create and store an array for all the p elements:
function dummyArray(){
var $dummy= $('p');
var dummy= [];
i = 0;
$dummy.each(function()
{
dummy[i++] =$(this).html();
});
return dummy;
}
Now, in order to reuse the array in another function, I can use dummyArray() and dummyArray()[0] to access the individual data.
function initAll(){
//dummyArray();
//dummyArray()[0];
}
However I want to store it inside a variable like below but it gives me error.
function initAll(){
var allArray = dummyArray();//error
}
Is there a way to store it inside a variable or is there a better way of doing this?

After cleaning up my code I noticed that using var allArray = dummyArray(); does work, the error was generated from something else. cheers~
Edited:
The error I found out was the function name cannot be the same as the new variable name declared even though the () aren't there.
var dummyArray = dummyArray();//error
var allArray = dummyArray();//works

Related

Save/Looad checkbox state by class name

I am trying to save and load the state of some checkbox:
function saveCheckbox () {
var a = document.querySelectorAll('input[type="checkbox"]');
var array = [];
a.forEach(function(checkBox){
array.push({className: checkBox.className, checked: checkBox.checked});
});
localStorage.setItem('Checkboxes', JSON.stringify(array));
console.log(JSON.stringify(array));
}
Seems to save fine, and checking the log as well, but when I try to load it, it doesnt work at all:
function loadCheckbox(){
var a = JSON.parse(localStorage.getItem('Checkboxes'));
a.forEach(function(checkBox){
document.getElementsByClassName(checkBox.className).checked =
checkBox.checked;
});
console.log(JSON.stringify(a));
}
What am I doing wrong here?
Trying declaring a with different varible name and use let in loadCheckbox()
let data = JSON.parse(localStorage.getItem('Checkboxes'));
This can be a typical hoisting related issue. In javascript it takes all the declared variable to the top before runtime. To avoid these you should use let where it uses the block scope of function.

Javascript Module Pattern accessing updated parameter value

I've tried to search for an answer to my question, but I'm starting to think that, given the lack of results, I'm obviously not expressing the question properly. With that in mind, apologies if the title of this post is misleading, I am still very much learning.
I have a simplified version of my code below
var testData = ['a', 'b']
var addReceiver = (function () {
dataReceiver = function (dataInput) {
t = this
t.data = dataInput;
console.log(t.data);
t.interval = setInterval(function () {
t.update();
}, 1000);
t.stopUpdate = function () { clearInterval(t.interval); };
t.update = function () {
//t.data = dataInput;
console.log(t.data);
};
};
})()
var testLogger = new dataReceiver(testData);
</script>
The behaviour that I wish to emulate is when I type into the console
testData = ['c','d','e']
for testLogger to log the array ['c','d','e'] every second rather than ['a','b'].
I could change
t.data = dataInput to t.data = testData
to achieve this, but that would obviously be pointless, or else every new instance I created of dataReceiver would have a reference to the same data input.
So, my question is, how would I need to change the code to provide the testLogger vairable (or any instance of dataReceiver) access to a variable outside of its local scope?
Use the object that you have created instead of accessing the global variable,
var testLogger = new dataReceiver(testData);
testLogger.data = [1,2,3,4];
Now you will be able to print the newly injected data. I mean the setInterval will print the updated value.

javascript function to save data in global variables

I have problems to make this function (addMe) to save the data from img and span from div childBox in two global arrays?
I think something is wrong in the function but can't see what.
This is my code.
Global var: //before function init
var imgSrclist = [];
var imgSpanlist = [];
Function:
function addMe(obj) {
var el = document.getElementById(obj.getAttribute('data-img'));
var parent = el.parentNode.getElementsByClassName('childBox')[0],
imgSRC = parent.getElementsByName('img')[0].src,
spanTXT = parent.getElementsByTagName('span')[0].innerHTML;
if (obj.checked) {
imgSpanlist[el.id].imgSrc.push(imgSRC);
imgSrclist[el.id].imgSpan.push(spanTXT);
} else {
var imgIx = imgSrclist[el.id].imgSrc.indexOf(imgSRC),
spanIx = imgSpanlist[el.id].imgSpan.indexOf(spanTXT);
imgSrclist[el.id].imgSrc.splice(imgIx);
imgSpanlist[el.id].imgSpan.splice(spanIx);
}
}
The data should be saved on global variabels because it will be used later in a new window when you push a button. The script code for the new windows starts with this:
var imgSrclist = window.opener.imgSrclist;
var imgSpanlist = window.opener.imgSpanlist;
EDIT: The code is now updated, so the arrays is declared. But the problem is that the imgsrc and span text dosenĀ“t comes to the new window. are they saved in the array at all?
Two things I want to mention is;
var imgSrclist;
var imgSpanlist;
should declare as an array and
function init() {
imgSrc=[]; //Empty array
imgSpan=[]; //Empty array
}
why they are declare as an array as you are not using these as an array.
I have updated two above changes, here is your code.

how to get a property name which represent a function in JS

This is some JS code
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr)
{
window[methodName] = function()
{
console.log(methodName);
}
}
My problem is that how to get the name of a function in JS.
In JS, use this.callee.name.toString() can get the function name. But in this situation, it is a null value. How can i get the 'funName' string?
Sorry, I didn't make it clear.
I want to create functions in a for loop, all these functions has almost the same implementation which need its name. But others can call these functions use different name.I want to know what methodName function is called.
it seems a scope problem.
Try this:
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr) {
var methodName = methodArr[i]; // <---- this line missed in your code?
window[methodName] = (function(methodName) {
return function() {
console.log(methodName);
}
})(methodName);
}
window['secondFunc'](); // output: secondFunc

Dynamic javascript function declaration

I'm working on a code where I must pass a different function to some objects.
In this case, I'm trying to pass a different function for the onchange event. So currently what I got is something like this this:
var ArrayList; //Contains some data to use with ObjectArray format { n: data }
var ObjectArray; //Contains several objects format Array[n] = Object;
for(var key in ArrayList){
var doFunction = function() {
Object[key].doSomething(ArrayList[key]);
}
Object[key].onchange = doFunction;
}
The problem here I believe is that I'm afraid it will execute the code as it is declared and not with the values of the actual variables.
Is there a way to pass the function with the values as it executes? or will the variables get parsed the way its written?
It's the classic function in a loop problem. You need to understand how closures work.
Read the "Example 3" part of this answer carefully. The whole How do JavaScript closures work? question, too.
Another example that might help understand intuitively:
var key = 5;
var onchange = function () {
console.log(key);
};
onchange(); // 5
key = 10; // the loop reassigns the key on each iteration
onchange(); // 10
This is how it should be done:
var ArrayList; //Contains some data to use with ObjectArray format { n: data }
var ObjectArray; //Contains several objects format Array[n] = Object;
for(var key in ArrayList)
{
(function(key)
{
var doFunction = function()
{
Object[key].doSomething(ArrayList[key]);
}
Object[key].onchange = doFunction;
}(key))
}

Categories

Resources