从文章:

发送一个JSON数组作为Dictionary<string,string>接收

我试图做同样的事情,因为那篇文章,唯一的问题是,我不知道什么键和值是前面。我需要动态添加键和值对,我不知道怎么做。

有人知道如何创建对象并动态添加键值对吗?

我试过了:

var vars = [{key:"key", value:"value"}];
vars[0].key = "newkey";
vars[0].value = "newvalue";

但这行不通。


当前回答

在现代javascript (ES6/ES2015)中,字典应该使用Map数据结构。ES6中的Map数据结构允许您使用任意值作为键。

const map = new Map();
map.set("true", 1);
map.set("false", 0);

在你仍在使用ES5的情况下,正确的创建字典的方法是按照下面的方法创建没有原型的对象。

var map = Object.create(null);
map["true"]= 1;
map["false"]= 0;

在没有原型对象的情况下创建字典有很多优点。下面的博客值得一读。

dict-pattern

objects-as-maps

其他回答

在现代javascript (ES6/ES2015)中,字典应该使用Map数据结构。ES6中的Map数据结构允许您使用任意值作为键。

const map = new Map();
map.set("true", 1);
map.set("false", 0);

在你仍在使用ES5的情况下,正确的创建字典的方法是按照下面的方法创建没有原型的对象。

var map = Object.create(null);
map["true"]= 1;
map["false"]= 0;

在没有原型对象的情况下创建字典有很多优点。下面的博客值得一读。

dict-pattern

objects-as-maps

你可以创建一个类Dictionary,这样你就可以轻松地与Dictionary列表交互:

类字典{ 构造函数(){ 这一点。Items = {}; } (关键){ 在this.items中返回键; } 集(关键字,值){ 这一点。项目[key] = value; } 删除(关键){ If (this.has(key)){ 删除this.items(例子) 返回true; } 返回错误; } } var d = new Dictionary(); d.set(“value1”) “value2 d.set (2) d.set(3,“value3”) console.log (d.has (2)); d.delete (2); console.log (d.has (2));

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
}

小提琴

var dict = {};

dict['key'] = "testing";

console.log(dict);

就像python一样工作:)

控制台输出:

Object {key: "testing"} 

我碰巧在寻找类似的东西时遇到了这个问题。它给了我足够的信息来进行测试,以得到我想要的答案。因此,如果有人想知道如何动态地添加或查找JavaScript对象中的{key: 'value'}对,这个测试应该会告诉你所有你可能需要知道的东西。

var dictionary = {initialkey: 'initialValue'};
var key = 'something';
var key2 =  'somethingElse';
var value = 'value1';
var value2 = 'value2';
var keyInitial = 'initialkey';

console.log(dictionary[keyInitial]);

dictionary[key] =value;
dictionary[key2] = value2;
console.log(dictionary);

输出

initialValue
{ initialkey: 'initialValue',
  something: 'value1',
  somethingElse: 'value2' }