How to increment an object property value if it exists, else set the initial value?

后端 未结 6 1483
谎友^
谎友^ 2021-01-31 14:54

How might I add check to see if a key already exists, and if does, increment the value, and if it doesn\'t exist, then set the initial value?

Something like this pseudo-

6条回答
  •  温柔的废话
    2021-01-31 15:55

    Your pseudo-code is almost identical to the actual code:

    if (key in object) {
        object[key]++;
    } else {
        object[key] = 1;
    }
    

    Although I usually write:

    if (!(key in object)) {
        object[key] = 0;
    }
    
    object[key]++;
    

提交回复
热议问题