views:

68

answers:

3

In the following code why the variable 'a' refer to the index rather than the value ?

 for  (var a in  Values) {

     alert(Values[a]);
 }
+8  A: 

That's by design. It's trivial to get a value in an array when you know its key, but it's much harder to get a key given a value. Values can be duplicated, so how do you know which key should be used? But a key's unique, so given a key, there's only ever one value to retrieve. So, the for loop will iterate over the keys, and it's trivial to get the associated value.

Marc B
For the op: "Keys" is interchangeable with index (0..n) if the object is an Array.
CD Sanchez
@Daniel: Sort of. If you add properties to the array or `Array.prototype`, they will be included in the loop as well.
Matthew Crumley
Thanks Matthew, Now I understand the design..
Frederic Torres
A: 

There is a for each...in loop that does exactly that - enumerates only values. Coming soon to a browser near you.

for each(var a in Values) {
    ..
}

For arrays, there is a new function forEach which achieves the same.

someArray.forEach(function(value) {
    ..
});
Anurag
+1  A: 

Think of a JavaScript Array as a normal Object with a special property named length (actually, it a bit more complex). So the for..in loop behaviour is identical as for other objects:

var a = new Array();

a[1] = "a";
alert(a.length); // 2
alert(a[0]); // undefined

a[1000] = "b"
alert(a.length); // 1001


a[-1] = "c";
alert(a[-1]); // c

a.abc="why not";

for(var key in a)
{
  alert(key+"="+a[key]);
}
// 1=a
// 1000=b
// -1=c
// abc=why not

Also note that you can have gaps within your array without having to pay the memory price.

gawi