var = {}和var = []之间的区别? [英] Difference between var = {} and var = []?

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

问题描述


可能重复:

Javascript中的对象与数组之间的键/值对

我在JavaScript中有一个变量,我使用的是 hash 。我可以将它初始化为:

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

var selected = [];

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 object and 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?

推荐答案

[] 是一个数组, {} 是一个对象。数组是一种只能分配数字键的对象。

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

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

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

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

// array:
'[]'

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

这篇关于var = {}和var = []之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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