-1

I'm adding a bunch of input fields into an associative array. I can access the individual elements fine, eg. this works:

arr = new Array();
field = document.getElementById("someField");
arr[field] = someValue;
alert(arr[field].id);

But when I try to loop over them, the id shows up as undefined, and only one element is looped over.

for (var elem in arr) {
    alert(elem.id + " " + arr[elem]);
}

Am I looping over it wrong?

Edit: arr.length shows up as 0 for some reason even though I'm able to access its elements.

idlackage
  • 2,715
  • 8
  • 31
  • 52

2 Answers2

1

Any associative array in JavaScript is an object. Arrays are objects that have special methods because they are numerically indexed. So your code should look something like this:

obj = {};
field = document.getElementById("someField");
obj[field] = someValue;

for (var p in obj) {
    alert(obj[p].id);
}
dezman
  • 18,087
  • 10
  • 53
  • 91
1

the key in a javascript-array has to be a number or string. field is automatically converted to a string with toString().

arr = new Array();
field = document.getElementById("someField");
var key = field.toString();
arr[key] = someValue;
alert(arr[key].id);

in your for-loop, you iterate the keys of that array. field.toString() in that case. and a string does not have a id-property.

this will work:

for (var elem in arr) {
    alert(arr[elem].id + " " + arr[elem]);
}

by the way toString() of a DOM-Element ist often a generic string like "[SpanElement]". if you try to add multiple span-elements, you're effectivle overriding the item with "[SpanElement]" as key and end up with just one element.

in respect to @user2736012 comments, i encourage everyone to read "JavaScript Associative Arrays Demystified"

mo.
  • 3,474
  • 1
  • 23
  • 20
  • The `key` can be any value, but it's automatically converted to a string. Your `field.toString()` isn't necessary, and won't give the desired result if you're expecting it to serialize the element or something. – user2736012 Sep 10 '13 at 18:09
  • it's for demonstrational purposes ;) – mo. Sep 10 '13 at 18:11
  • I didn't know about the string/number restriction. Changed it to work with strings only and it's good now, thanks! – idlackage Sep 10 '13 at 18:18
  • @idlackage: There is no string/number restriction. It'll accept any value that can be converted to a string, which in JavaScript is any value. It's just that you'll get the string conversion as the key. Also, this answer is still using the wrong type. The `Array` should not be used here. – user2736012 Sep 10 '13 at 18:27