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 に答える