检查 JavaScript 中除零外是否为假

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31626876/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:05:02  来源:igfitidea点击:

Check if falsy except zero in JavaScript

javascriptstandards

提问by mortensen

I am checking if a value is not falsy with

我正在检查一个值是否不假

if (value) {
  ..
}

but I do want to accept zeros as a (non-falsy) value. How is this normally done? Would it be

但我确实想接受零作为(非假)值。这通常是如何完成的?可不可能是

if (value || value === 0) {
  ..
}

or what?

要不然是啥?

回答by vinayakj

if (value || value === 0) {
  ..
}

is cleaner way, no problem.

是更清洁的方式,没问题。

Just for fun try this

只是为了好玩试试这个

val = 0;
if(val){
console.log(val)
}
//outputs 0   **update - it used to be.. but now it seems it doesnt in chrome

And

var val = 0;
if(val){
console.log(val)
}
//outputs nothing

回答by RK.

I would use value || value === 0. It's fine whichever way you do it but IMO this is the cleanest option.

我会使用value || value === 0. 无论您采用哪种方式都可以,但 IMO 这是最干净的选择。