为什么我可以将命名属性添加到数组中,就好像它是一个对象一样? [英] Why can I add named properties to an array as if it were an object?

查看:26
本文介绍了为什么我可以将命名属性添加到数组中,就好像它是一个对象一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于为什么我可以将命名属性添加到数组中,就好像它是一个对象一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆