简体   繁体   中英

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 , ...

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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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