Javascript var = {} 和 var = [] 的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12097851/
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 07:06:34  来源:igfitidea点击:

Difference between var = {} and var = []?

javascript

提问by Gil Birman

Possible Duplicate:
Objects vs arrays in Javascript for key/value pairs

可能的重复:
键/值对的 Javascript 中的对象与数组

I have a variable in JavaScript which I am using like a hash. I can initialize it like:

我在 JavaScript 中有一个变量,我像hash一样使用它。我可以像这样初始化它:

var selected = [];

or

或者

var selected = {};

and it does the same exact thing. I'm using it like this for example:

它做同样的事情。例如,我正在使用它:

selected["one"] = 1;

if (selected["one"] == 1) console.log("one is selected"); 
// result: one is selected

if (selected["two"] != 1) console.log("two is not selected");
// result: two is not selected

selected["one"] = 0;

if (selected["one"] != 1) console.log("one is no longer selected");
// result: one is no longer selected

Is there really a difference? Is one an objectand the other an array? If so, when should I expect to run into problems. Ie., what is the difference between the two in their usage, and why would you chose one over the other?

真的有区别吗?一个是对象,另一个是数组?如果是这样,我什么时候应该会遇到问题。即,两者在用法上有什么区别,为什么你会选择一个而不是另一个?

回答by Niet the Dark Absol

[]is an array, {}is an object. An array is a type of object intended to be only assigned numeric keys.

[]是一个数组,{}是一个对象。数组是一种旨在仅分配数字键的对象。

While you can in theory use them interchangably, look what happens when you JSON-ify them:

虽然理论上你可以互换使用它们,但看看当你 JSON 化它们时会发生什么:

var tmp = []; // or: var tmp = {}
tmp.one = 1;
JSON.stringify(tmp);

// array:
'[]'

// object:
'{"one":1}'

回答by apsillers

An Array ([]) is a kind ofObject ({}). The key differences are:

数组 ( []) 是一种对象 ( {})。主要区别是:

  • Arrays have a magic lengthproperty that is equal to the highest-set numeric key (plus one):

    var a = [];
    a[100] = 0;
    a.length; // is 101
    
    var o = {};
    o[100] = 0;
    o.length; // is undefined
    
  • An Array's toStringmethod prints out the values of numeric keys:

    var a = [];
    a[0] = 5;
    a[1] = 6;
    a[2] = 7;
    a.toString(); // "[5,6,7]"
    
    var o = {};
    o[0] = 5;
    o[1] = 6;
    o[2] = 7;
    o.toString(); // "[object Object]"
    
  • Arrays have lots of specific functions for processing records:

    > Object.getOwnPropertyNames(Array.prototype)
    ["join", "toLocaleString", "sort", "some", "lastIndexOf", "splice", "map",
     "constructor", "every", "unshift", "shift", "indexOf", "pop", "forEach", "reverse",
     "reduce", "slice", "concat", "filter", "toString", "reduceRight", "push", "length"]
    
  • 数组有一个魔法length属性,它等于设置最高的数字键(加一):

    var a = [];
    a[100] = 0;
    a.length; // is 101
    
    var o = {};
    o[100] = 0;
    o.length; // is undefined
    
  • Array 的toString方法打印出数字键的值:

    var a = [];
    a[0] = 5;
    a[1] = 6;
    a[2] = 7;
    a.toString(); // "[5,6,7]"
    
    var o = {};
    o[0] = 5;
    o[1] = 6;
    o[2] = 7;
    o.toString(); // "[object Object]"
    
  • 数组有很多用于处理记录的特定函数:

    > Object.getOwnPropertyNames(Array.prototype)
    ["join", "toLocaleString", "sort", "some", "lastIndexOf", "splice", "map",
     "constructor", "every", "unshift", "shift", "indexOf", "pop", "forEach", "reverse",
     "reduce", "slice", "concat", "filter", "toString", "reduceRight", "push", "length"]
    

回答by Matchu

Yup, {}is an empty object and []is an empty array. Note that an array isa kind of object, optimized to handle a list of values, but, like any Javascript object, it can accept other attributes like "one"or "two"— which is how it can support methods like myArray.push(1): pushis an attribute of all arrays. In fact, you can even say myArray["push"] = someOtherFunctionto override pushwithout any trouble. Arrays, like all Javascript objects, support arbitrary key-value assignments.

{}是的,是一个空对象,[]是一个空数组。请注意,数组一种对象,经过优化以处理值列表,但是,与任何 Javascript 对象一样,它可以接受其他属性,例如"one"or "two"— 这就是它如何支持诸如myArray.push(1):push是所有数组的属性之类的方法。事实上,你甚至myArray["push"] = someOtherFunction可以push毫无困难地说覆盖。数组,像所有 Javascript 对象一样,支持任意键值分配。

Ultimately, though, it has to do with behind-the-scenes performance. If you're looking to store a sequential list of values, the array will handle it much better and offer some helpful attributes like push, shift, length, etc. — plus, future developers will actually know what you're doing. If you're looking to just store key-value pairs, the object is the way to go, since it's not bogged down by all that extra weight.

不过,归根结底,这与幕后表演有关。如果你正在寻找存储值的顺序列表,阵列将更好的处理,并提供像一些有用的属性pushshiftlength,等-加,未来开发商将真正知道自己在做什么。如果您只想存储键值对,那么对象是最佳选择,因为它不会被所有额外的重量所困扰。

In short, while they both support key-value pairs, they're very different behind the scenes. Don't worry too much about it and use whichever lends itself better to the job at hand.

简而言之,虽然它们都支持键值对,但它们在幕后却大不相同。不要太担心它,使用最适合手头工作的方法。

回答by robbrit

Using {}is an object, which is the basis for every complex type in Javascript. The reason you can treat an array like an object is because in Javascript an array isan object (but not the other way around).

Using{}是一个对象,它是 JavaScript 中每个复杂类型的基础。您可以将数组视为对象的原因是因为在 Javascript 中,数组一个对象(但不是相反)。

The square brackets in Javascript are the way you access an object's attributes, much like the .notation in C, Java, Python, etc. It just so happens that arrays have values at attribute 0, 1, 2, etc. Arrays also have a whole bunch of other built-in attributes like length, shift, push, etc.

JavaScript 中的方括号是您访问对象属性的方式,很像.C、Java、Python 等中的符号。碰巧数组在属性 0、1、2 等处具有值。数组也有一个整体一堆其他内置的属性,如lengthshiftpush,等。

This is an oversimplification for sure, however it's an easy way to understand what's going on.

这肯定是过于简单化了,但这是了解正在发生的事情的一种简单方法。

回答by Pablo Grisafi

An Array is an Object, but an Object is not (always) an Array. An Array has methods and properties not present in every object Example

一个数组是一个对象,但一个对象并不(总是)一个数组。数组具有并非在每个对象中都存在的方法和属性示例

[].length //0
{}.length //undefined
typeof []['slice'] //function
typeof {}['slice'] //undefined

If you use an array as a hashmap and try to use as a key something already present you will get into trouble

如果您使用数组作为哈希图并尝试使用已经存在的东西作为键,您会遇到麻烦

回答by Bruno

[]is for arrays and {}is for plain objects. Note that an arrayis an object with a number of methodsand properties that allow to model lists (e.g. push, slice, ...).

[]用于数组和{}用于普通对象。请注意,数组是一个具有许多方法和属性的对象,这些方法和属性允许对列表进行建模(例如推送、切片等)。

As pointed out in the MDN documentation, you shouldn't use an array as an associative array, i.e. arrays are not to be used as hash tables.

正如 MDN 文档中所指出的,您不应该将数组用作关联数组,即数组不能用作哈希表。

回答by Novak

The first is an array, the second is a literal object:

第一个是array,第二个是literal object

var a = {};
a.SomeProperty = 1;

console.log(a.SomeProperty);

var b = [];
b['SomeProperty'] = 2;

console.log(b['SomeProperty']);

This will output 1and 2in the console logs.

这将在控制台日志中输出12

For hashing, use an array(WRONG), thanks for the comment.

For hashing, use an array错误),感谢您的评论。