How to increment a value in a JavaScript object?

前端 未结 7 1015
时光说笑
时光说笑 2021-02-12 13:50
var map = {};
map[key] = value;

How can I

  • assign value 1 if key does not yet exist in the object
  • increment the value by 1 if it
7条回答
  •  无人及你
    2021-02-12 14:08

    ES6 provides a dedicated class for maps, Map. You can easily extend it to construct a "map with a default value":

    class DefaultMap extends Map {
    
        constructor(defVal, iterable=[]) {
            super(iterable);
            this.defVal = defVal;
        }
    
        get(key) {
            if(!this.has(key))
                this.set(key, this.defVal);
            return super.get(key);
        }
    }
    
    m = new DefaultMap(9);
    console.log(m.get('foo'));
    m.set('foo', m.get('foo') + 1);
    console.log(m.get('foo'))

    (Ab)using Objects as Maps had several disadvantages and requires some caution.

提交回复
热议问题