Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

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

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-code:

var dict = {};
var new_item = "Bill"

If new_item not in dict:
dict[new_item] = 1

else:

dict[new_item] += 1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
dict[key] = (dict[key] || 0) + 1;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...