javascript |
您所在的位置:网站首页 › 字典添加key › javascript |
字典增加方式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";请注意,键(属性名称)始终是字符串,非字符串值在用作键时将强制转换为字符串。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |