抱歉,当涉及到JavaScript时,我有点新手。但是这是我的问题:
当输入0时,以下函数返回-1。
function foo(bar){
return bar || -1;
}
foo(0);
有没有一种简洁优雅的方法来允许||操作符将0(特指0,而不是所有falsy值)作为有效值读取,以便函数返回0?还是我必须这样做:
function foo(bar){
if(bar === 0){
return 0;
} else {
return bar || -1;
}
}
foo(0);
编辑:
感谢大家的回答!对于那些想知道的人,这个问题是为了寻找可选参数相同问题的解决方案而提出的。以下代码是应用示例。
function Point(x,y,meta){ //meta is an optional parameter. In this case I wanted to set meta to 0, but it was being set to null.
this.x = x;
this.y = y;
//this.meta = meta || null; This line is the old code that would set meta to null when 0 is inputed.
this.meta = meta === 0 ? 0 : (meta || null); //the fix suggested by many users is applied here.
};
var foo = new Point(1,2,0);
console.log(foo.meta); //foo.meta is now 0 instead of null!
-1
呢?假值包括undefined
,null
,false
,+0
,-0
,NaN
,""
。 - Oriolfoo(Infinity)
这里你期望得到什么输出? - Willem D'Haeseleer