-3

version a:

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

does not work. No output in console see here:

How can I make version a work?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Toskan
  • 13,911
  • 14
  • 95
  • 185

2 Answers2

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);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Shadow
  • 8,749
  • 4
  • 47
  • 57