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

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

提交回复
热议问题