How to create dictionary and add key–value pairs dynamically?

后端 未结 15 744
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 00:37

From post:

Sending a JSON array to be received as a Dictionary

I’m trying to do this same thing as that post. The only issue is that I d

15条回答
  •  情歌与酒
    2020-11-28 01:30

    JavaScript's Object is in itself like a dictionary. No need to reinvent the wheel.

    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
    }
    

    Fiddle

提交回复
热议问题