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

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

    You should check if the object has an own property with the new_item name first. If it doesn't, add it and set the value to 1. Otherwise, increment the value:

    var dict = {};
    var new_item = "Bill"
    
    dict[new_item] = dict.hasOwnProperty(new_item)? ++dict[new_item] : 1;
    

    The above is a bit wasteful as if the property exists, it increments it, then assigns the new value to itself. A longer but possibly more efficient alternative is if the property doesn't exist, add it with a value of zero, then increment it:

    if (!dict.hasOwnProperty(new_item)) {
      dict[new_item] = 0;
    }
    ++dict[new_item];
    

提交回复
热议问题