0

这是我拥有的 JavaScript

var testArr = [];
testArr["foo"] = "bar";
console.log(testArr.toSource());
//console.log(testArr["foo"]); //logs "bar"

我得到的输出是[],这不是我所期望的。有人可以解释这里发生了什么吗?

4

2 回答 2

0
// This declares an array
var testArr = [];

// THis assign an object property.  Because it isn't a numeric array index,
// it doesn't show up as part of the array.
testArr["foo"] = "bar";

// .toSource() is not cross platform. 
// JSON.stringify(testArr, undefined, 2) is better
console.log(testArr.toSource());

// Yes, because that property exists.
//console.log(testArr["foo"]); //logs "bar"

It sounds like what you really want is this:

// Make an object that can take string properties and not just integer indexes.
var testObject = {};
于 2012-09-18T14:09:19.607 回答
0

出色地。w3schools 说它在 IE 上不起作用。

此外,我已经在 Chrome 中执行了它,并且即使打印了> testArr也打印了一个典型的控制台。所以我认为在输出源时关联数组不会被迭代。[]> testArr["foo"]bar

尝试将第一行更改为:

var testArr = {};

这样,它将是一个共同的对象。

于 2012-09-18T13:40:57.933 回答