javascript 如果存在,如何增加对象属性值,否则设置初始值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18690814/
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 an object property value if it exists, else set the initial value?
提问by user1813867
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
回答by snak
dict[key] = (dict[key] || 0) + 1;
回答by SimplGy
@snak's way is pretty clean and the ||
operator makes it obvious in terms of readability, so that's good.
@snak 的方式非常干净,并且||
操作员在可读性方面使其显而易见,所以这很好。
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:
这是有效的,因为在强制转换为 Number 后~~
会将许多非数字的东西变成0
。我知道这不是一个非常完整的解释,但这里是一些不同场景的输出:
~~(null)
0
~~(undefined)
0
~~(7)
7
~~({})
0
~~("15")
15
回答by Blender
Your pseudo-code is almost identical to the actual code:
您的伪代码几乎与实际代码相同:
if (key in object) {
object[key]++;
} else {
object[key] = 1;
}
Although I usually write:
虽然我通常写:
if (!(key in object)) {
object[key] = 0;
}
object[key]++;
回答by James LeClair
You can use the ternary operator (?:) like this:
您可以像这样使用三元运算符 (?:):
dictionary[key] ?
dictionary[key].value += 1 :
dictionary[key] = {value: 1};
回答by RobG
You should check if the object has an own property with the new_itemname first. If it doesn't, add it and set the value to 1. Otherwise, increment the value:
您应该首先检查对象是否具有自己的属性,名称为new_item。如果不是,添加它并将值设置为 1。否则,增加值:
var dict = {};
var new_item = "Bill"
dict[new_item] = dict.hasOwnProperty(new_item)? ++dict[new_item] : 1;
The above is a bit wasteful as if the property exists, it increments it, then assigns the new value to itself. A longer but possibly more efficient alternative is if the property doesn't exist, add it with a value of zero, then increment it:
上面有点浪费,好像属性存在一样,它增加它,然后将新值分配给它自己。更长但可能更有效的替代方法是,如果该属性不存在,则将其添加为零值,然后将其递增:
if (!dict.hasOwnProperty(new_item)) {
dict[new_item] = 0;
}
++dict[new_item];
回答by Macro
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:
您可以通过多种方式做到这一点。一般来说,如果你想知道Object
一个键是否有键,你可以使用in
带有键名的修饰符。这看起来像:
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:
虽然您可以通过简单的测试来检查是否设置了值undefined
。这就是在 JavaScript 中,如果您没有初始化值并通过 if 语句发送它,它将充当 false。看起来像:
var dict = {};
if(dict["key"]) {
print("key: " + dict[key]);
} else {
print("Missing key");
}