Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: cannot loop dynamic array through $.each

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

var array = [];
array['one'] = 'two';
$.each(array, function( key, value )
{
    //not get in loop
    alert(value);
});
like image 574
Sevi Avatar asked Dec 05 '22 15:12

Sevi


1 Answers

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.

like image 139
Barmar Avatar answered Dec 22 '22 08:12

Barmar