-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?

6
  • 1
    That's not an array with string indexes. It's an array with two properties that you have tacked onto it. The length is still 0. If you want to iterate through the properties, you can use Object.keys(x). Commented Nov 2, 2017 at 3:45
  • 1
    Don't use an array for this. Use an object: var x = {} Commented Nov 2, 2017 at 3:46
  • how is that a duplicate?..... This is a common pitfall. Commented Nov 2, 2017 at 4:06
  • You can simply use for-in: for(var _x in x){ console.log(_x,":",x[_x]); } Commented Nov 2, 2017 at 4:11
  • @Toskan Um, it's a duplicate because it's a common pitfall. Commented Nov 2, 2017 at 7:52

2 Answers 2

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>

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

Comments

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>

2 Comments

so what exactly did I do to my array?
Use an object instead. {} instead of [].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.