如何增加 JavaScript 对象中的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39590858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to increment a value in a JavaScript object?
提问by membersound
var map = {};
map[key] = value;
How can I
我怎样才能
- assign value 1 if key does not yet exist in the object
- increment the value by 1 if it exists
- 如果对象中尚不存在键,则分配值 1
- 如果存在则将值增加 1
Could I do better than:
我能做得更好吗:
if (map[key] == null) map[key] = 0;
map[key] = map[key]++;
回答by ricky
Here you go minimize your code.
在这里,您可以最小化您的代码。
map[key] = (map[key]+1) || 1 ;
回答by Alex Char
You can check if the object doesn't have the specific key and set it or increase existing key value by one:
您可以检查对象是否没有特定键并设置它或将现有键值增加一:
function assignKey(obj, key) {
typeof obj[key] === 'undefined' ? obj[key] = 1 : obj[key]++;
}
var map = {};
assignKey(map, 2);
assignKey(map, 2);
assignKey(map, 4);
assignKey(map, 1);
assignKey(map, 2);
assignKey(map, 5);
assignKey(map, 1);
console.log(map);
回答by georg
ES6 provides a dedicated class for maps, Map
. You can easily extend it to construct a "map with a default value":
ES6 为地图提供了一个专门的类,Map
. 您可以轻松扩展它以构建“具有默认值的地图”:
class DefaultMap extends Map {
constructor(defVal, iterable=[]) {
super(iterable);
this.defVal = defVal;
}
get(key) {
if(!this.has(key))
this.set(key, this.defVal);
return super.get(key);
}
}
m = new DefaultMap(9);
console.log(m.get('foo'));
m.set('foo', m.get('foo') + 1);
console.log(m.get('foo'))
(Ab)using Objects as Maps had several disadvantages and requires some caution.
(Ab) 使用对象作为地图有几个缺点,需要谨慎。
回答by Mercury
function addToMap(map, key, value) {
if (map.has(key)) {
map.set(key, parseInt(map.get(key), 10) + parseInt(value, 10));
} else {
map.set(key, parseInt(value, 10));
}
}
回答by gopigorantala
Creating an object:
创建对象:
tagObject = {};
tagObject['contentID'] = []; // adding an entry to the above tagObject
tagObject['contentTypes'] = []; // same explanation as above
tagObject['html'] = [];
Now below is the occurrences entry which I am addding to the above tag Object..
现在下面是我添加到上面标签对象的出现条目。
ES 2015 standards:function () {}
is same as () => {}
ES 2015 标准:function () {}
与() => {}
let found = Object.keys(tagObject).find(
(element) => {
return element === matchWithYourValueHere;
});
tagObject['occurrences'] = found ? tagObject['occurrences'] + 1 : 1;
this will increase the count of a particular object key..
这将增加特定对象键的计数..
回答by nirmal
It would be better if you convert array's value into integer and increment it. It will be robust code. By default array's value is string. so in case you do not convert it to integer then it might not work cross browser.
如果将数组的值转换为整数并递增它会更好。这将是健壮的代码。默认情况下,数组的值为字符串。因此,如果您不将其转换为整数,那么它可能无法跨浏览器工作。
if (map[key] == null) map[key] = 0;
map[key] = parseInt(map[key])+1;