简体   繁体   English

如何增加字典中的键?

[英]How to increment a key in the dictionary?

I'm new to javascript and I'm trying to increment a key in the dictionary我是 javascript 新手,我正在尝试增加字典中的一个键

 var dic = {} for (let i = 0; i < 100; i++) { dic['key']++ } console.log(dic)

I don't get the incremented number, where am I going wrong?我没有得到递增的数字,我哪里出错了?

You are trying to increment undefined since there is no key property in dic , thus you get NaN .您正在尝试增加undefined因为dic没有key属性,因此您得到NaN

Instead, give the key property a default value:相反,给key属性一个默认值:

 var dic = {key: 0} for (let i = 0; i < 100; i++) { dic['key']++ } console.log(dic)

var dic = { count1: 0, count2: 10 }

for (var i in dic) {
    if (i === 'count1') {
        dic[i]++;
    }
}
console.log(dic);

Are you trying to do anything like this?你想做这样的事情吗? here you are iterating through the object, if i equals the key you are looking for, it will increment it.在这里,您正在遍历对象,如果 i 等于您要查找的键,它将增加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM