声明 JavaScript 数组时,“{}”和“[]”之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33514915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:10:16  来源:igfitidea点击:

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

javascriptarraysobjectjavascript-objectsdeclaration

提问by Venkat

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

声明 JavaScript 数组时,“{}”和“[]”之间有什么区别?通常我声明像

var a=[];

What is the meaning of declaring the array as var a={}

将数组声明为什么意思 var a={}

回答by jfriend00

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

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

[]is declaring an array.

[]正在声明一个数组。

{}is declaring an 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.

数组具有对象的所有特性以及附加特性(您可以将数组视为对象的子类),其中在 Array 子类中添加了附加方法和功能。事实上,typeof [] === "object"为了进一步向您展示数组是一个对象。

The additional features consist of a magic .lengthproperty 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.

附加的功能包括一个神奇的.length属性,跟踪数组中的项目数和方法的阵列,如在操作整体转换的.push().pop().slice().splice(),等...你可以看到的阵列方法的列表在这里

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

Object properties can be accessed either via the x.foosyntax 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.foosyntax.

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

A property name can be any string value.

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



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, sequentiallist of numbered indexes starting from 0and 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.

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

回答by Roli Agrawal

When you declare

当你声明

var a=[];

you are declaring a empty array.

您正在声明一个空数组。

But when you are declaring

但是当你声明

var a={};

you are declaring a Object .

您正在声明一个 Object 。

Although Array is also Object in Javascript but it is numeric key paired values. Which have all the functionality of object but Added some few method of Array like Push,Splice,Length and so on.

虽然 Array 也是 Javascript 中的 Object 但它是数字键配对值。它具有对象的所有功能,但添加了一些数组方法,如 Push、Splice、Length 等。

So if you want Some values where you need to use numeric keys use Array. else use object. you can Create object like:

因此,如果您想要某些需要使用数字键的值,请使用 Array。否则使用对象。您可以创建对象,如:

var a={name:"abc",age:"14"}; 

And can access values like

并且可以访问像

console.log(a.name);

回答by Hemina

var a = [];

it is use for brackets for an array of simple values. eg.

它用于简单值数组的括号。例如。

var name=["a","b","c"]

var a={}

is use for value arrays and objects/properties also. eg.

也用于值数组和对象/属性。例如。

var programmer = { 'name':'special', 'url':'www.google.com'}

回答by Rahul Tripathi

It can be understood like this:

可以这样理解:

var a= []; //creates a new empty array
var a= {}; //creates a new empty object

You can also understand that

你也可以这样理解

var a = {};is equivalent to var a= new Object();

var a = {};相当于 var a= new Object();

Note:

笔记:

You can use Arrays when you are bothered about the order of elements(of same type) in your collection else you can use objects. In objects the order is not guaranteed.

当您对集合中元素(相同类型)的顺序感到困扰时,您可以使用数组,否则您可以使用对象。在对象中,不保证顺序。

回答by Tomer W

they are two different things..

他们是两个不同的东西..

[]is declaring an Array:
given, a list of elements held by numeric index.

[]正在声明一个数组:
给定,由数字索引保存的元素列表。

{}is declaring a new object:
given, an object with fields with Names and type+value,
some like to think of it as "Associative Array". but are not arrays, in their representation.

{}正在声明一个新对象:
给定,一个带有名称和类型+值的字段的对象,
有些人喜欢将其视为“关联数组”。但在它们的表示中不是数组。

You can read more @ This Article

你可以阅读更多@这篇文章

回答by Michael Eden

In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.

在 JavaScript 中,数组和对象实际上非常相似,尽管在外观上它们可能看起来有些不同。

For an array:

对于数组:

var array = [];
array[0] = "hello";
array[1] = 5498;
array[536] = new Date();

As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain anytype of variable! That's pretty convenient.

正如您所看到的,JavaScript 中的数组可以是稀疏的(有效索引不必是连续的)并且它们可以包含任何类型的变量!这很方便。

But as we all know JavaScript is strange, so here are some weird bits:

但是我们都知道 JavaScript 很奇怪,所以这里有一些奇怪的地方:

array["0"] === "hello"; // This is true
array["hi"]; // undefined
array["hi"] = "weird"; // works but does not save any data to array
array["hi"]; // still undefined!

This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.

这是因为 JavaScript 中的一切都是对象(这就是为什么您也可以使用 来创建数组new Array())。因此,数组中的每个索引都被转换为字符串,然后存储在对象中,因此数组只是一个对象,不允许任何人使用非正整数的键存储任何内容。

So what are Objects?

那么什么是对象呢?

Objects in JavaScript are just like arrays but the "index" can be any string.

JavaScript 中的对象就像数组,但“索引”可以是任何字符串。

var object = {};
object[0] = "hello"; // OK
object["hi"] = "not weird"; // OK

You can even opt to not use the square brackets when working with objects!

在处理对象时,您甚至可以选择不使用方括号!

console.log(object.hi); // Prints 'not weird'
object.hi = "overwriting 'not weird'";

You can go even further and define objects like so:

您可以更进一步定义对象,如下所示:

var newObject = {
    a: 2,
};
newObject.a === 2; // true

回答by riteshkasat

Syntax of JSON

JSON 的语法

object = {} | { members }

对象 = {} | {成员}

  • members = pair | pair, members
  • pair = string : value
  • 成员 = 对 | 对, 成员
  • 对 = 字符串:值

array = [] | [ elements ]

数组 = [] | [元素]

  • elements = value | value elements
  • 元素 = 值 | 价值要素

value = string|number|object|array|true|false|null

值 = 字符串|数字|对象|数组|真|假|空