Monday, August 5, 2019

jquery - Can't push items into array from anonymous callback function in Javascript



I'm having a javascript issue that's driving me completely insane. I have a collection of data that I'm iterating over using the jQuery .each() method. Inside the .each() callback function, I'm pushing data on the an array. Here's the code.



var p = procedure_tool.all();
previousValue = -1;
var proceduresArray = [];
p.each(function(d, proceduresArray) {
proceduresArray.push(d.procedureID);
});



I've also tried making the proceduresArray global (no var in front), and then trying not to pass it through the anonymous function.



var p = procedure_tool.all();
previousValue = -1;
proceduresArray = [];
p.each(function(d) {
proceduresArray.push(d.procedureID);
})



The data does exist (alerts inside the callback display it fine). Any ideas? I feel like it's a scope issue, but I figure that globalizing the array would have fixed it.



Thanks


Answer



Two things,



1- You don't need to pass the proceduresArray to the anonymous function.
2- The anonymous function in .each() is passed 2 things. The first is the index of the element and the second is the element. I.e. callback(indexInArray, valueOfElement) http://http://api.jquery.com/jQuery.each/




This should work just fine:



var p = procedure_tool.all();
previousValue = -1;
var proceduresArray = [];
p.each(function(i, d) {
proceduresArray.push(d.procedureID);
});



Another example:



var p = $('div');
var pArray = [];

p.each(function(i, el)
{
pArray.push(el);
});


console.log(pArray);


Keep in mind the value can also be accessed using this within the anonymous function.




No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...