简短的 javascript 代码:初始化为零或递增
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13298232/
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
short javascript code for: initialize to zero or increment
提问by Geert-Jan
I love those short js oneliners. I'd like to know if there's something logical and elegant for:
我喜欢那些简短的 js oneliners。我想知道是否有一些合乎逻辑和优雅的东西:
- intializing a variable to zero if undefined
- increment by one otherwise.
- 如果未定义,则将变量初始化为零
- 否则加一。
Shorter than this preferrably ;)
最好比这短;)
var obj = {} ;
//some iterative called function
obj.prop = obj.prop===undefined?0:obj.prop++;
回答by I Hate Lazy
This will result in NaN
for the first increment, which will default to 0
.
这将导致NaN
第一个增量,默认为0
。
obj.prop = ++obj.prop || 0;
回答by Bogdan D
A cleaner way of doing this is simply
一种更简洁的方法很简单
obj.prop = obj.prop + 1 || 0;
Using the increment operator is wrong or overkill. The suffixed operator, x++
, (the example in the question) should not work at all. The prefixed, ++x
, leads to assigning twice (like saying x = x = x+1
)
使用增量运算符是错误的或矫枉过正的。后缀运算符 , x++
(问题中的示例)根本不应该起作用。前缀 ,++x
导致分配两次(就像说x = x = x+1
)
回答by bormat
A shorter solution: obj.prop = -~obj.prop
更短的解决方案:obj.prop = -~obj.prop
回答by Данила Летуновский
It is not possible to directly pass a variable to the function inc(obj.prop), because in javascript variables are passed by value, but you can pass the object itself and the name of the variable you want to increment.
不能直接将变量传递给函数 inc(obj.prop),因为在 javascript 中变量是按值传递的,但是您可以传递对象本身和要递增的变量的名称。
Object.prototype.inc = function(n){ this[n]? this[n]++ : this[n] = 1; }
let obj = {};
obj.inc("prop");
// obj.prop == 1
You can also add the required fields to the object before
您还可以在对象之前添加必填字段
Object.prototype.has_fields = function(obj2){
for(let p of Object.keys(obj2)){
if(obj2[p].constructor == Object){
if(!this[p]) this[p] = {};
this[p].has_fields(obj2[p]);
}else{
if(!this[p]) this[p] = obj2[p];
}
}
return this;
}
let obj = {};
obj.has_fields({a:{b:{c:{d:{prop:0}}}}});
obj.a.b.c.d.prop++;
// obj.a.b.c.d.prop == 1
obj.has_fields({a:{b:{c:{d:{prop:0}}}}});
obj.a.b.c.d.prop++;
// obj.a.b.c.d.prop == 2
回答by aljgom
Similar to I Hate Lazy's answerbut avoids the double assignment as Bodganpoints out
类似于I Hate Lazy 的回答,但避免了Bodgan指出的双重分配
++obj.prop || (obj.prop=0)
in the global scope
在全球范围内
++window.foo || (window.foo=0)