简体   繁体   English

Javascript 关联数组在变量声明上有所不同

[英]Javascript associative arrays differ on variable declaration

I notice a difference when I declare a variable as an array or object and then add elements to it.当我将变量声明为数组或对象然后向其中添加元素时,我注意到了不同之处。

When I declare my variable as below:当我声明我的变量如下:

var my_array = [];
my_array["a"] = 'first';
my_array["b"] = 'second';
console.log(my_array);

I get the following result:我得到以下结果:

[a: "first", b: "second"] 

However, when I do the following:但是,当我执行以下操作时:

var my_array = {};
my_array["a"] = 'first';
my_array["b"] = 'second';
console.log(my_array);

This is the result I get:这是我得到的结果:

Object {a: "first", b: "second"} 

What is really going on here?!这到底是怎么回事?! Is one way standard, and the other not?!一种方式是标准的,另一种方式不是?! What are the downsides with compatibility?!兼容性有什么缺点?!

Thanks in advance.提前致谢。

PS I'm using Google Chrome. PS我正在使用谷歌浏览器。

The first is an array and the secound is an object, which one to use depands on your goal, if you need arrays the array will be more usefull and effiecent than using an "array" object.第一个是一个数组,第二个是一个对象,使用哪个取决于您的目标,如果您需要数组,该数组将比使用“数组”对象更有用和有效。

Further more an object can be used like this: myObject.a此外,可以像这样使用对象: myObject.a

While an array can be only used like this: myArray["a"]虽然数组只能这样使用: myArray["a"]

Another diffrence is in the toString method.另一个不同之处在于toString方法。 For an array it returns Banana,Orange,Apple,Mango (for example) and for an object it returns [object Object] (for example).对于数组,它返回Banana,Orange,Apple,Mango (例如),对于一个对象,它返回[object Object] (例如)。

For further reading: What is the difference between an array and an object?进一步阅读: 数组和对象有什么区别?

Check if is array:检查是否是数组:

function isArray(obj) {
    return Object.prototype.toString.call(obj) === "[object Array]";
}

They are two different objects.它们是两个不同的对象。 I use the second for JSON response, and the first for normal use in the code.我将第二个用于 JSON 响应,第一个用于代码中的正常使用。

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

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