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

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

Related

How to let user defined mehods not being iliterated in a for in statement [duplicate]

This question already has answers here:
Why is using "for...in" for array iteration a bad idea?
(28 answers)
How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop
(4 answers)
Closed 1 year ago.
This is the piece code to show my question:
var data=[];
for(var pro in data) {
console.log('Property: '+pro);
}
Array.prototype.Dummy=function() {
};
for(var pro in data) {
console.log('Property:'+pro);
}
I expect the 2 for in statements behave the same, the first prints nothing, reasonable, but the second one will list 'Dummy' only as the array's property, even Array has lots of buildin methods.
The user defined method is different from build in, why?
The reason I ask this question is that I use 3 party libraries, if I extend buildin data types(like Array, Date ect.), I'll potentially modify what their for in statements do.

How to get array out of object in JS [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I was trying to get data from the notes array in the data object. I'm getting the object from mongodb and I want to get the array called notes. but I can't do it. for some reason. In java there is like Object.get(notes) and I can get a specific field within the object but I don't know how to do that in js. And I haven't been able to find something that works elsewhere online.
here is my code
axios.post('/api/user/notes')
.then(res => {
console.log( Object.values(res.data));
dataSet = Object.values(res.data);
console.log(dataSet[0]);
console.log(dataSet.notes[0]);
}).catch(err => {
console.log('it didnt work' + err);
});
image
dataSet is an array. So, to get the notes, you have to first select the first element of data, dataSet[0] and then the notes array. To get the first note, it would be dataSet[0].notes[0]. Also, beware that you are setting a global variable (perhaps on a browser's window object) when you type dataSet = ... What you probably want is to declare a variable local to the function with var dataSet = ...

Unable to access an array where the contents of said array are visible in Console.Log [duplicate]

This question already has answers here:
How can I make console.log show the current state of an object?
(12 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I setup a global variable to hold the data array:
var data = [];
This is a global variable as it is used outside of a function and needs to be accessible for all functions
I then iterate over a data set and populate the data array.
When I access this array using the console:
console.log(window.data);
I can see the following in Chromes console view:
There are many more records in the data set, they all follow exactly the same format
The issue I am having is, I cannot access this data array and am seeing zero length as shown below:.
console.log(window.data.length); // returns 0
I'm not clear on why this is occurring and am hoping someone can point out what I am doing wrong.
It seems like the result of processing this array is not available at the time I am trying to get the length, therefore I am getting zero.
Have tried the following at the end of the html file:
$( document ).ready(function() {
console.log("ready!"); // returns ready!
console.log(window.data[15]); // returns undefined
});
Not quite sure how to proceed, so any advice would be very welcome.
EDIT:
This was resolved by the use of promises (bottom link in the duplicate notice above).
Previous code was removed as it didn't add to the discussion and would probably only create confusion
Core issue was based on data not being available on page load due to processing of large arrays.

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);
});
}

Javascript - refilling one array from another [duplicate]

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.

Categories