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

后端 未结 6 1550
谎友^
谎友^ 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");
    }
    

提交回复
热议问题