gpt4 book ai didi

Javascript 逻辑运算符 ||读取 0 作为假值。有解决这个问题的好方法吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:01:41 26 4
gpt4 key购买 nike

抱歉,我对 JavaScript 有点菜鸟。但这是我的问题:以下函数在输入0时返回-1

function foo(bar){
return bar || -1;
}

foo(0);

有没有一种优雅的方式允许 ||运算符读取 0(特别是 0,不是所有虚假值)作为有效值,以便函数返回 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!

最佳答案

这就是 JavaScript 的工作方式。所有值要么为真,要么为假。零恰好是一个虚假的值(value)。不过,您可以使用三元来简化函数。

function foo(bar) {
return bar === 0 ? 0 : (bar || -1);
}

关于Javascript 逻辑运算符 ||读取 0 作为假值。有解决这个问题的好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com