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

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

    You can do this in a lot of ways. In general if you want to know if an Object has a key you use the in modifier with the key name. This looks like:

    var key = "key name";
    var dict = {};
    var hasKey = (key in dict);
    

    Though you can check if a value is set by simply testing if it is undefined. This being that in JavaScript if you don't have a value initialized and send it through an if statement it will act as a false. Which looks like:

    var dict = {};
    if(dict[key]) {
       print("key: " + dict[key]);
    } else {
       print("Missing key");
    }
    
    0 讨论(0)
  • 2021-01-31 15:30

    @snak's way is pretty clean and the || operator makes it obvious in terms of readability, so that's good.

    For completeness and trivia there's this bitwise way that's pretty slick too:

    dict[key] = ~~dict[key] + 1;
    

    This works because ~~ will turn many non-number things into 0 after coercing to Number. I know that's not a very complete explanation, but here are the outputs you can expect for some different scenarios:

    ~~(null)
    0
    ~~(undefined)
    0
    ~~(7)
    7
    ~~({})
    0
    ~~("15")
    15
    
    0 讨论(0)
  • 2021-01-31 15:39
    dict[key] = (dict[key] || 0) + 1;
    
    0 讨论(0)
  • 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];
    
    0 讨论(0)
  • 2021-01-31 15:53

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

    dictionary[key] ? 
        dictionary[key].value += 1 : 
        dictionary[key] = {value: 1};
    
    0 讨论(0)
  • 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]++;
    
    0 讨论(0)
提交回复
热议问题