字典增加方式1
var dict = {};
dict['key'] = "testing";
console.log(dict);
像python一樣工作:)
控制台輸出:
Object {key: "testing"}
字典增加方式2
var blah = {}; // make a new dictionary (empty)
##
var blah = {key: value, key2: value2}; // make a new dictionary with two pairs
##
blah.key3 = value3; // add a new key/value pair
blah.key2; // returns value2
blah['key2']; // also returns value2
參考
javascript - 如何動態創建字典和添加鍵值對? - ITranslater
其他方法參數
var dict = []; // create an empty array
dict.push({
key: "keyName",
value: "the value"
});
// repeat this last part as needed to add more key/value pairs
或者在創建對象后使用常規點符號設置屬性:
// empty object literal with properties added afterward
var dict = {};
dict.key1 = "value1";
dict.key2 = "value2";
// etc.
如果您有包含空格的鍵,特殊字符或類似的東西,您確實需要括號表示法。 例如:
var dict = {};
// this obviously won't work
dict.some invalid key (for multiple reasons) = "value1";
// but this will
dict["some invalid key (for multiple reasons)"] = "value1";
如果您的鍵是動態的,您還需要括號表示法:
dict[firstName + " " + lastName] = "some value";
請注意,鍵(屬性名稱)始終是字符串,非字符串值在用作鍵時將強制轉換為字符串。