4

Why cannot loop an dynamic array through $.each()?

var array = [];
array['one'] = 'two';
$.each(array, function( key, value )
{
    //not get in loop
    alert(value);
});
0

1 Answer 1

14

For an array, $.each() only loops through the numbered indexes. If you want to loop through named properties, you have to use an object.

var obj = {};
obj['one'] = 'two';
$.each(obj, function( key, value )
{
    console.log(key, value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

This is explained in the documentation:

Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

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

5 Comments

if you want to use an array change the second line of the OP code to array[0] = 'two';
I think when he says "dynamic array" he means something with named properties.
Might be worth pointing out the dot notation for an object, also - is very handy to know how to use both bracket and dot notation....
@cale_b Again, his reference to "dynamic" implies that it will be a variable, and he just used a literal for the MCVE.
Wow. I was not aware of this till now. Life saver :)

Your Answer

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