zyxue zyxue - 4 months ago 17
Javascript Question

why the type of a number element in an array is evaluated to be a string in javascript

For example



var a = [1, 2, 3];
for (var i in a) {
console.log(typeof i);
}





Output



string
string
string


I am a Python programmer, and I find it very unintuitive. Why is not an element evaluated to be a number instead?

Answer

why the type of a number element in an array is evaluated to be a string in javascript

If you really mean the element, not the index, then the problem is that you're just looking at the type of the wrong thing. See KevBot's answer.


If you're asking why the indexes (0, 1, and 2) are strings rather than numbers, since array indexes are normally numbers, it's because standard arrays in JavaScript aren't really arrays at all, they're just objects with some special behavior:

An Array object is an exotic object that gives special treatment to array index property keys (see 6.1.7). A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 232. The value of the length property is numerically greater than the name of every own property whose name is an array index; whenever an own property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever an own property is added whose name is an array index, the value of the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the value of the length property is changed, every own property whose name is an array index whose value is not smaller than the new length is deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.

Until ES2015, all object property names were strings. (Now they can be either strings or Symbols.) Array indexes are just property names that conform to a specific definition:

A String property name P is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 232-1.

See also A myth of arrays (on my blog).