Skip to content Skip to sidebar Skip to footer

Why Does $.each() Not Work With Arrays That Have A String Index In Jquery?

version a: does not work. No output in console see here: How can I make version a work?

Solution 1:

From 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.

Since x is an array, only its numeric properties are considered, not its named properties. Since it doesn't have any of these, nothing is printed.

You make it work by using an object instead of an array.

var x = {};
x['abc'] = 'd';
x['xyz'] = 'abbb';
$.each(x, function(i, el) {
  console.error(el);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Solution 2:

There is no such thing as an associative array in javascript. We have objects. Your current code using an object instead of an array should do the trick.

var x = {};  // Note that we're using curly brances
x["abc"] = 123;
x["def"] = 456;

$.each(x, function(key, value){
   console.log(key, value);
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Post a Comment for "Why Does $.each() Not Work With Arrays That Have A String Index In Jquery?"