这是我的JavaScript
var testArr = [];
testArr["foo"] = "bar";
console.log(testArr.toSource());
//console.log(testArr["foo"]); //logs "bar"
我得到的输出是[]
,这不是我所期待的。有人能解释一下这里发生了什么吗?
答案 0 :(得分:0)
好。 w3schools表示它不适用于IE。
此外,我已在Chrome中执行此操作,并且即使> testArr
打印[]
,> testArr["foo"]
也打印了bar
。所以我认为在输出源时不会迭代关联数组。
尝试将第一行更改为:
var testArr = {};
这将是一个共同的目标。
答案 1 :(得分: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 = {};