简体   繁体   English

在这种情况下,我应该使用大括号{}或方括号[]吗?

[英]Should I use curly brackets {} or square brackets [] in this case?

Currently I have an array using an increasing index: 目前我有一个使用增加索引的数组:

var idx = 1;
var a = [];
a[idx++] = "apple";
a[idx++] = "orange";
...
console.log(a[2]);

And only accessing it by [] , not using array specific functions, like length , indexOf , ... 并且只能通过[]访问它,而不是使用数组特定的函数,如lengthindexOf ,...

Apparently following is also working in this case: 显然,以下情况也适用于这种情况:

var a = {};

So, which one should I prefer in such case? 那么,在这种情况下我应该选择哪一个? For example any performance difference between them? 例如它们之间的任何性能差异?

[ ] denotes an array. []表示一个数组。 Arrays only hold values: 数组只包含值:

var a1 = [1, 2, 3, 4]

As @Qantas pointed out, array can hold more than just values. 正如@Qantas指出的那样,数组可以容纳的不仅仅是值。 An array can even contain another array and/or object: 数组甚至可以包含另一个数组和/或对象:

var a2 = [1, 2, ["apple", "orange"], {one: "grape", two: "banana"}];

{ } denotes an object. {}表示一个对象。 Objects have key-value pairs like 对象具有键值对

var a3 = {one: 1, two: 2}

In your case, it's really a matter of how you would like to be able to access the data. 在您的情况下,这实际上是您希望如何访问数据的问题。 If you are only interested in knowing "apple", "pear", etc. Go ahead and use an array. 如果您只对“苹果”,“梨”等感兴趣,请继续使用阵列。 You can access it via it's index 您可以通过它的索引访问它

a1[0]; // outputs 1
a1[1]; // outputs 2

or you can iterate over it with a loop. 或者你可以用循环迭代它。 If you use the curly braces, (given the example I gave) you could access it with 如果你使用花括号(给定我给出的例子)你可以用它来访问它

a3.one; // outputs 1
a3["two"]; // outputs 2

It's really up to you on how it would best fit your needs in this case. 在这种情况下,最重要的是它如何最符合您的需求。 For a more extensive discussion see this article . 有关更广泛的讨论,请参阅此文章

The difference is using square brackets will create an Array object while using curly brackets creates a plain object. 区别在于使用方括号将创建一个Array对象,而使用花括号创建一个普通对象。 For example: 例如:

a = [];
a[1] = 'a';

b = {};
b[1] = 'b';

a.length; // returns 2
b.length; // is undefined

a.push('z'); // add 'z' to the end of a
b.push('z'); // generates an error - undefined is not a function
             // because plain objects don't have a push method

Read the MDN documentation on Array objects to know more about arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array 阅读有关Array对象的MDN文档,了解有关数组的更多信息: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM