开发者

JS associative arrays: add new pair

I have an associa开发者_如何转开发tive array in JS.

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

How can I add new pair in it


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

or

array.newpair = 'newvalue';

This is quite a decent read on the subject.


It's an object literal, not really an "associative array".

Just do array['something'] = 'something';


(Maybe a bit late, but very useful for future devs)

Instead of trying to make associative array or creating your own object, I'd suggest https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map It is more handy ;)

// 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜