什么是一个数组和对象之间的区别? [英] What is the difference between an array and an object?

查看:163
本文介绍了什么是一个数组和对象之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的两个不同的code片段似乎等同于我:

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)(包括产量'对象')

有这些变体有什么区别?

推荐答案

几乎所有的JavaScript是一个对象,这样你就可以滥用的<一个href=\"https://developer.mozilla.org/En/Core%5FJavaScript%5F1.5%5FReference/Global%5FObjects/Array\">Array通过它设置任意属性对象。这应该被考虑,虽然有害。数组是数字索引数据 - 非数字键,使用对象

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天全站免登陆