0

I have the loop below:

        var myArray = [];
        $(this).children('a').each(function () {
            myArray.push($(this).attr('href'));
        });

which fires 3 times. When I look inside that array, I see that there is only one (last added) item. Why ?

2
  • 3
    What is this code inside of? If you're inside another function or loop, you're resetting the myArray each time you get to it. Commented Jan 16, 2012 at 18:31
  • Is this the entire code? Commented Jan 16, 2012 at 18:33

2 Answers 2

3

Because you use declare myArray as a local variable. If you want the array's values to persist, move var myArray = []; outside the common function.

var myArray = []; // This variable is shared by all instances of somefunction
$('#example').click(function() {
    $(this).children('a').each(function () {
        myArray.push($(this).attr('href'));  //myArray in the parent scope
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

it's declared outside the jquery function, so i don't think this it the problem. + it does has one value...
@gdoron I don't see all of the code. It's perfectly possible that the OP invokes the function using .click().click().click() = 3 triggers. Still, if var myArray = []; is inside the click event handler, the array will only be locally available.
1

I'd suggest using for loops as they are much faster.

http://jsperf.com/jquery-each-vs-for-loop/44

Try this:

var myArray = [],
    links = $("a.link");
for (var i = 0, l = links .length; i < l; i++) {
    myArray.push($(links[i]).attr("href"));
}
console.log(myArray);

Comments

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.