javascript function to save data in global variables - javascript

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.

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.

Updating an array returned by a function

I've been trying to implement some card game using Javascript. In the snippet below, I simply want to pull two cards from the top of the deck and give it to the player (simplified logic below)
function deck() {
var faceCards = [['jack', 11],['queen', 12],['king', 13]];
return faceCards;
}
function removeCard() {
var singleCard = deck().pop();
var faceValue = singleCard[0];
return faceValue;
}
var cardPair = [removeCard(),removeCard()];
console.log(cardPair);
However the faceCards array is still the same even after popping off its cards which means that the next card will be the same as well as seen in cardPair array.
I need to mirror the effects I used inside of the
removeCard() function to reflect back in the deck() function.
I suppose I could either create the faceCards array in the global scope or use 'this' in some way (which I don't really want as I'm not much familiar with it). How can I update one function from inside another function? Thank you very much for reading this.
Your error is here:
var singleCard = deck().pop()
The call to deck() creates a new array of cards every time it's called, and doesn't repeatedly return the same array.
If you don't want to go full OO yet, consider at least passing the deck as a parameter to the removeCard() function, i.e.
function removeCard(deck) {
var singleCard = deck.pop();
var faceValue = singleCard[0];
return faceValue;
}
var deck = newDeck();
var pair = [ removeCard(deck), removeCard(deck) ];
but ultimately you should longer term be going for a full OO solution, where your usage might then become:
var deck = new Deck();
var pair = [ deck.takeCard(), deck.takeCard() ];
implementation of this is out of scope of this particular question.
You're creating a new array every time you run deck(). Try saving the deck in an array and running pop on this:
function deck() {
var faceCards = [['jack', 11],['queen', 12],['king', 13]];
return faceCards;
}
function removeCard(fromDeck) {
var singleCard = fromDeck.pop();
var faceValue = singleCard[0];
return faceValue;
}
var thisDeck = deck();
var cardPair = [removeCard(thisDeck),removeCard(thisDeck)];
console.log(cardPair);

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.

Create variable to JavaScript array from another function?

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

Array syntax error newbie

I am lost in this error. I am trying to write a function and write a array in that function. in an external js file. This is going to be a random image loading function but i keep getting an error with the array and can't figure out why.
function randImg(){
var imgs = new Array();
img[0]="banner1.png";
img[1]="banner2.png";
img[2]="banner3.png";
var maxium = img.length;
}
I am getting the error on the var imgs line. any ideas?
Here is my new code calling the variable "img" was throwing me off it loads ok but it only prints out the text in the variable and not the actually file!? so at run it say "banner1.png" or "banner3.png"? any thoughts
function randImg(){
var banner = new Array();
banner[0] = "banner1.png";
banner[1] = "banner2.png";
banner[2] = "banner3.png";
var maxImg = banner.length;
var randNum = Math.floor(Math.random()*maxImg);
return banner[randNum];
}
A better way to define the array with its elements:
var img = [
"banner1.png",
"banner2.png",
"banner3.png",
"banner4.png"
]
And this is the function you might need:
function randImg(){
var img = [
"banner1.png",
"banner2.png",
"banner3.png",
"banner4.png"
]
var maxImg = img.length;
var randNum = Math.floor(Math.random()*maxImg)
return img[randNum]
}
Your variable names should be consistent. You created the new Array imgs (local variable), yet you added to img (defaulted to global variable, since you didn't declare it a local variable).
Also, note that in Javascript it doesn't make too much sense to add a var statement that is not the first line of a function. This is because of hoisting. Essentially, Javascript will take your var and move it to the first line, setting the variable to undefine. This may or may not affect how your program works vs how you think it should work, so it's best to add all your vars at the top of your functions. Javascript has function scope, not block scope.
(also note that maximum is a more meaningful variable name than maxium)
// This adds to the newly created array:
function randImg(){
var img = new Array(), // Note: img NOT imgs
maximum; // Even if a var is below this line, Javascript hoists it here
img[0] = "banner1.png";
img[1] = "banner2.png";
img[2] = "banner3.png";
maximum = img.length;
}
and you can use .push() if you're just adding to the end of an array (like you're doing)
function randImg(){
var img = new Array(), // Note: img NOT imgs
maximum;
img.push("banner1.png");
img.push("banner2.png");
img.push("banner3.png");
maximum = img.length;
}
or
function randImg(){
var img = new Array(), // Note: img NOT imgs
maximum;
img.push("banner1.png").push("banner2.png").push("banner3.png)";
maximum = img.length;
}
or better yet, just use [] to initialize an empty array or [a,b,c,...] to initialize an array with elements. Also, why use var twice?
function randImg(){
var img = ["banner1.png","banner2.png","banner3.png"], // note comma
maximum = img.length;
}
Finally, to live up to the name of the function
var randImg = function() {
var img = ["banner1.png","banner2.png","banner3.png"];
return img[Math.floor(Math.random()*img.length)];
}
... and here's a working example of randImg()

Categories

Resources