从文章:
发送一个JSON数组作为Dictionary<string,string>接收
我试图做同样的事情,因为那篇文章,唯一的问题是,我不知道什么键和值是前面。我需要动态添加键和值对,我不知道怎么做。
有人知道如何创建对象并动态添加键值对吗?
我试过了:
var vars = [{key:"key", value:"value"}];
vars[0].key = "newkey";
vars[0].value = "newvalue";
但这行不通。
从文章:
发送一个JSON数组作为Dictionary<string,string>接收
我试图做同样的事情,因为那篇文章,唯一的问题是,我不知道什么键和值是前面。我需要动态添加键和值对,我不知道怎么做。
有人知道如何创建对象并动态添加键值对吗?
我试过了:
var vars = [{key:"key", value:"value"}];
vars[0].key = "newkey";
vars[0].value = "newvalue";
但这行不通。
当前回答
var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1
其他回答
创建键值对的一行代码怎么样?
let result = { ["foo"]: "some value" };
还有一些迭代器函数,比如reduce,可以动态地将数组转换为字典
Var选项= [ {key: "foo",值:1}, {key: "bar",值:{id: 2,名称:"two"}}, {key: "baz", value: {["active"]: true}}, ]; Var result = options。Reduce((累加器,电流)=> { 蓄电池(电流。键]= current.value; 返回蓄电池; }, {}); console.log(结果);
对var dict ={}的改进是使用var dict = Object.create(null)。
这将创建一个没有object的空对象。原型就是原型。
var dict1 = {};
if (dict1["toString"]){
console.log("Hey, I didn't put that there!")
}
var dict2 = Object.create(null);
if (dict2["toString"]){
console.log("This line won't run :)")
}
var dict = {};
dict['key'] = "testing";
console.log(dict);
就像python一样工作:)
控制台输出:
Object {key: "testing"}
JavaScript的Object本身就像一个字典。没有必要重新发明轮子。
var dict = {};
// Adding key-value -pairs
dict['key'] = 'value'; // Through indexer
dict.anotherKey = 'anotherValue'; // Through assignment
// Looping through
for (var item in dict) {
console.log('key:' + item + ' value:' + dict[item]);
// Output
// key:key value:value
// key:anotherKey value:anotherValue
}
// Non existent key
console.log(dict.notExist); // undefined
// Contains key?
if (dict.hasOwnProperty('key')) {
// Remove item
delete dict.key;
}
// Looping through
for (var item in dict) {
console.log('key:' + item + ' value:' + dict[item]);
// Output
// key:anotherKey value:anotherValue
}
小提琴
你可以在Map中使用地图,像这样:
var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');