JS关联数组:添加新对

时间:2011-08-04 05:35:20

标签: javascript arrays dictionary associative-array

我在JS中有一个关联数组。

var array = {
    'one' : 'first',
    'two' : 'second',
    'three' : 'third'
};

如何在其中添加新配对

3 个答案:

答案 0 :(得分:22)

array['newpair'] = 'new value';

array.newpair = 'newvalue';

This is quite a decent read on the subject

答案 1 :(得分:3)

它是一个对象文字,而不是一个“关联数组”。

只需array['something'] = 'something';

答案 2 :(得分:0)

(可能有点晚,但对未来的开发者非常有用)

与其尝试创建关联数组或创建自己的对象,不如建议 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map 它更方便;)

// Eg. 1
let wrongMap = new Map()
wrongMap['bla'] = 'blaa'
wrongMap['bla2'] = 'blaaa2'

console.log(wrongMap)  // Map { bla: 'blaa', bla2: 'blaaa2' }

// Eg .2
let contacts = new Map()
contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
contacts.has('Jessie') // true
contacts.get('Hilary') // undefined
contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})
contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"}
contacts.delete('Raymond') // false
contacts.delete('Jessie') // true
console.log(contacts.size) // 1