声明 JavaScript 数组时,“{}"和“[]"之间有什么区别? [英] What’s the difference between “{}” and “[]” while declaring a JavaScript array?

查看:44
本文介绍了声明 JavaScript 数组时,“{}"和“[]"之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在声明 JavaScript 数组时,{}"和[]"有什么区别?通常我声明像

What’s the difference between "{}" and "[]" while declaring a JavaScript array? Normally I declare like

var a=[];

将数组声明为var a={}

推荐答案

似乎没有人解释数组和对象之间的区别.

Nobody seems to be explaining the difference between an array and an object.

[] 正在声明一个数组.

{} 正在声明一个对象.

数组具有对象的所有特性,并具有附加特性(您可以将数组视为对象的子类),其中在 Array 子类中添加了附加方法和功能.实际上,typeof [] === "object" 是为了进一步说明数组是对象.

An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class. In fact, typeof [] === "object" to further show you that an array is an object.

附加功能包括一个神奇的 .length 属性,它跟踪数组中的项目数量和一系列用于操作数组的方法,例如 .push(), .pop(), .slice(), .splice() 等等...你可以看到一个数组方法列表此处.

The additional features consist of a magic .length property that keeps track of the number of items in the array and a whole slew of methods for operating on the array such as .push(), .pop(), .slice(), .splice(), etc... You can see a list of array methods here.

对象使您能够将属性名称与值相关联,如下所示:

An object gives you the ability to associate a property name with a value as in:

var x = {};
x.foo = 3;
x["whatever"] = 10;
console.log(x.foo);      // shows 3
console.log(x.whatever); // shows 10

对象属性可以通过x.foo 语法或类似数组的语法x["foo"] 访问.后一种语法的优点是您可以使用变量作为属性名称,例如 x[myvar] 并且使用后一种语法,您可以使用包含 Javascript 不允许的字符的属性名称x.foo 语法.

Object properties can be accessed either via the x.foo syntax or via the array-like syntax x["foo"]. The advantage of the latter syntax is that you can use a variable as the property name like x[myvar] and using the latter syntax, you can use property names that contain characters that Javascript won't allow in the x.foo syntax.

属性名称可以是任何字符串值.

A property name can be any string value.

数组是一个对象,因此它具有对象的所有相同功能以及一系列用于管理有序顺序编号索引列表的附加功能,从0 并达到一定的长度.数组通常用于按数字索引访问的项目的有序列表.而且,因为数组是有序的,所以有很多有用的功能来管理列表的顺序 .sort() 或者从列表中添加或删除内容.

An array is an object so it has all the same capabilities of an object plus a bunch of additional features for managing an ordered, sequential list of numbered indexes starting from 0 and going up to some length. Arrays are typically used for an ordered list of items that are accessed by numerical index. And, because the array is ordered, there are lots of useful features to manage the order of the list .sort() or to add or remove things from the list.

这篇关于声明 JavaScript 数组时,“{}"和“[]"之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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