2

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

1 Answer 1

3

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.

  • Christian
Sign up to request clarification or add additional context in comments.

1 Comment

While this didn't solve my problem directly, it did highlight another oversight. I was using the .each() iterator (which is generally used for DOM elements) instead of jQuery.each() iterator which is meant to iterate over any object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.