Javascript - refilling one array from another [duplicate] - javascript

This question already has answers here:
Copy array by value
(39 answers)
Closed 8 years ago.
I'm creating a simple question and answer game to help with revision and having trouble repopulating an array the second time around.
When a button is clicked the following code is executed.
if(setSelection == 0){
tempQuestions = chosenQuestion;
tempAnswers = chosenAnswer;
}
This works perfectly the first time.
When a correct answer is selected the following code removes the question and answer from temporary array, leaving the original intact.
tempQuestions.splice(randomQuestion,1)
tempAnswers.splice(selectedAnswer, 1);
When the button is pressed for a second time, after the 'game' is complete, the temporary array fails to refill even though I'm executing the same code.
Any ideas why the code above does not work on the second run?
EDIT
jsfiddle

You are creating a new reference to the same array, so when you modify the temp vars you also modify the object referenced by the chosen vars. You need to copy the array. A nice way is to add your own copy() prototype method to the Array object.
a shallow copy should do:
Array.prototype.copy = function(){
return this.slice(0);
}
If you need a deep copy
Array.prototype.copy = function(){
return JSON.parse(JSON.stringify(this));
}
Use it like this:
if(setSelection == 0){
tempQuestions = chosenQuestion.copy();
tempAnswers = chosenAnswer.copy();
}

Using .slice works.
tempQuestions = chosenQuestion.slice();
The slice() operation clones the array and returns reference to the original.

Related

Same random number twice [duplicate]

This question already has answers here:
console.log() shows the changed value of a variable before the value actually changes
(7 answers)
Closed 3 years ago.
Why does this show the same random number twice when you run it in your console?
var arr = [[]];
arr[0][0] = Math.random();
console.log(arr);
arr[0][0] = Math.random();
console.log(arr);
I derived this root issue from another post, which was not getting much attention, and I'm wondering if anyone has a clear explanation of what's going on here. I know there are things you can do to make this work as expected, but I'm interested in knowing why it doesn't work as expected right now. It's acting as if console.log() waits until everything else is through to log anything.
The console.log shows a reference to the array, the moment you expand it it retrieves the latest array value with the latest Math.random() value.
The following demo shows this:
var test = [1,2,3];
console.log(test)
test.push(4)
console.log(test)
The preview shows the old values but when expanding the values it retrieves it using the pointer and thus gets the new values.

Add .change() to every variable in js Array(); [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I'm trying to create "dynamic" cascading dropboxes, and I almost have it done. However, I'm running into an issue dealing with adding a .change() listener onto every variable inside of an array that contains the <select> field ids.
So if I use:
fields[0].change(function() {populateFields(1, 0, xml);});
fields[1].change(function() {populateFields(2, 1, xml);});
The code works perfectly. However, I would prefer to use something like this:
for (i=1; i<numberOfFields; i++){
p = i-1; current = i;
fields[p].change(function() {populateFields(current, p, xml);});
}
So that I can have a variable number of fields, because the current code is limited to three fields. The for loop currently works, but doesn't work after the second field is entered.
Any help would be appreciated.
NOTE: This is not a question about variables or passing variables into functions, but rather adding a event listener to an array. The marked answer was the correct answer.
You can use Array.prototype.forEach(), and in the function that you pass in you can put a guard for the case where you are processing the first element:
fields.forEach(attachChangeHandler);
function attachChangeHandler(field, i) {
if (i === 0) { return; }
field.change(function() {
populateFields(i + 1, i, xml);
});
}

Finding specific objects in array to remove [duplicate]

This question already has answers here:
Best way to find if an item is in a JavaScript array? [duplicate]
(8 answers)
Closed 7 years ago.
I have an array of data which stores an object with functions and other such info. I push these objects to the function for my draw function to execute.
But i do not know of a way to find a specific object in an array to remove it and thus stop drawing it.
For example i have an array structure like this:
var data = {
'fnc':function(){
updatePosition(spriteID);
drawSprite(spriteID);
},
'something':'here'
};
var drawOrder= [];
drawOrder.push(data);
There are many functions in this array and they are pushed dynamically depending on what i wish to draw.
What would be the best way to find the index of one of these objects and remove it from the array in this case?
indexOf() returns the index in the array of the element you're searching for, or -1. So you can do:
var index = drawOrder.indexOf("aKey");
if (index != -1)
drawOrder.splice(index, 1);
Splice:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
indexOf:
http://www.w3schools.com/jsref/jsref_indexof_array.asp
I'm not 100% this will answer your question cause is not clear at least to me.
If you want to remove the whole element but you are worried about founding the right index before actually splice the array you should use Array.indexOF
See this code below:
var data = {
'fnc':function(){
updatePosition(spriteID);
drawSprite(spriteID);
},
'type':'aabb'
};
var drawOrder= [];
drawOrder.push(data);
console.log(drawOrder);
drawOrder.splice(drawOrder.indexOf(data), 1);
console.log(drawOrder);
As the documentation reports:
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Why reusing emptied array in Javascript not possible? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 7 years ago.
I programmed in a few programming languages, from time to time i have some experience also with Javescript.
Here my situation: I have an array as global variable (myArray). I need to refill myArray with data from the DB when some event happens. So I wrote myFunction, in which myArray is emptied to remove eventual older data, then filled again with the new data.
If I don't delete the array content, everything works, but (of course) the array may contain also older data and will grow each time the function is called, and I don't want that.
What I don't understand is the following:
If I delete the content of myArray when myFunction starts, I cannot refill it again...
Here the simplified version of my code, thanks everyone for any help:
myArray = []; // global variable
// IN MYFUNCTION
//first empty the array, then refill it with data from DB
{
// Let's empty myArray, tried all 4 different ways to do that -- no difference:
// Way 1)
//while(myArray.length > 0) { myArray.pop(); }
//OR Way 2)
//myArray.length=0;
//OR Way 3)
//myArray.splice(0,myArray.length);
//OR Way 4)
myArray = [];
dataNamesQuery = "SELECT something FROM db according user's input";
DatabaseInterface.get_data_now(dataNamesQuery).get({}, function(result){
allDataNames = result.Results;
for(i in allDataNames){
myArray.push(allDataNames[i].something);
}
});
}
//IF I DELETE THE CONTENT OF MYARRAY, THIS WILL PRINT NOTHING;
//ELSE IF I DON'T DELETE ITS CONTENT, THE ARRAY CONTAINS NEW AND OLD DATA
for(ix in myArray){
console.log("in myArray got " + myArray[ix]);
}
} //MYFUNCTION END
--edits--
I see that this question is marked as duplicated, maybe it is, just I couldn't find a question that suited to this situation.
I see from answers you listed that maybe the problem is in synchronization, so I have to learn about this topic

Moving element inside an object in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Array rotate()
I have a tricky question for you. I have an object who contain different values and I want to change the index of on element so My first element has to become the last or the third or whatever I want. Is that possible in javascript ??
var object = [{0},{1},{2}]
to
var object = [{2},{0},{1}]
This is an example of what I would like to do.
Thanks in advance.
Your from and to example is a little hard to understand the intent, but based on the body of your question asking
My first element has to become the last or the third or whatever I want
Writing a method to swap 2 elements in an array is easy enough:
function swapElements(a, x, y){
var temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Live example: http://jsfiddle.net/pwY9L/
I assume you mean:
var array = [0,1,2];
It doesn’t really matter if the array contains numbers, objects or whatever. If you want to modify this array, there are many ways to do this in javascript andyou can read up about all the Array prototypes here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
F.ex, move the last one and place it first:
array.unshift(array.pop());

Categories