我正在检查一个值是否不是错误的
if (value) {
..
}但我确实希望接受零作为(非falsy)值。这通常是如何完成的?会不会是
if (value || value === 0) {
..
}不然呢?
发布于 2015-07-25 21:21:18
if (value || value === 0) {
..
}是更干净的方式,没问题。
只是为了好玩,试试这个
val = 0;
if(val){
console.log(val)
}
//outputs 0 **update - it used to be.. but now it seems it doesnt in chrome和
var val = 0;
if(val){
console.log(val)
}
//outputs nothing发布于 2015-07-25 21:23:20
我会使用value || value === 0。不管你用哪种方式都很好,但我认为这是最干净的选择。
发布于 2021-10-22 11:39:30
3常用的条件检查:
if(! value ) { //一些非假值}
if(typeof value!== 'undefined') { //值存在且已定义}
if (value || value === 0) { ....}
https://stackoverflow.com/questions/31626876
复制相似问题