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

后端 未结 6 1480
谎友^
谎友^ 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:53

    You can use the ternary operator (?:) like this:

    dictionary[key] ? 
        dictionary[key].value += 1 : 
        dictionary[key] = {value: 1};
    

提交回复
热议问题