为什么我可以将命名属性添加到数组中,就好像它是一个对象一样?

以下两个不同的代码片段对我来说似乎等效:

The following two different code snippets seem equivalent to me:

var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";

var myObject = {'A': 'Athens', 'B':'Berlin'};

因为它们的行为相同,而且 typeof(myArray) == typeof(myObjects) (都产生 'object').

because they both behave the same, and also typeof(myArray) == typeof(myObjects) (both yield 'object').

这些变体之间有什么区别吗?

推荐答案

实际上 javascript 中的一切都是一个对象,所以你可以滥用"一个 Array 对象通过在其上设置任意属性.这应该被认为是有害的.数组用于数字索引数据 - 对于非数字键,请使用 Object.

Virtually everything in javascript is an object, so you can "abuse" an Array object by setting arbitrary properties on it. This should be considered harmful though. Arrays are for numerically indexed data - for non-numeric keys, use an Object.

这里有一个更具体的例子,说明为什么非数字键不能适应"数组:

Here's a more concrete example why non-numeric keys don't "fit" an Array:

var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";

alert(myArray.length);

这不会显示2",而是0" - 实际上,没有向数组添加任何元素,只是向数组对象添加了一些新属性.

This won't display '2', but '0' - effectively, no elements have been added to the array, just some new properties added to the array object.

相关文章