我理解就布尔值而言
x = true;
if(x) //This is the same as if(x === True)
doSomething();
但如果要将x设置为数字,那么if条件是什么意思? 该条件是否意味着(x === true)?如果是这样,为什么会这样?
答案 0 :(得分:2)
在javascript中,以下是 falsey
false
undefined
null
0
""
NaN
除上述内容之外的任何内容都是 truthy ,包括0
以外的数字。因此,10
是一个真值,因此执行if
块。
答案 1 :(得分:0)
简称如下:
//!length = if(x.length);
var a; //undefined == if(!a) == !length
var b = ""; //void == if(!b)
var c = " "; //blank == if(c) == length
var d = "text"; //there == if(d) == length
var e = true; //true == true == if(e)
var f = false; //false == false == if(!f)
var g = null; //false == if(!g) == !length
var h = 0; //0 == if(!h)
var i = 1; //true == if(i)
var j = 0/0; //NaN == if(!j)
var k = document.body; // == if(k)
var l = document.getElementById("nothing"); // if(!l) == !length
Javascript在检查“null
”值方面非常灵活。我猜你实际上在寻找空字符串,在这种情况下,这个更简单的代码将起作用:
if(!blah){
将检查空字符串(""
),null
,undefined
,false
以及数字0
和NaN
var a; //undefined == if(!a) == !length
var b = ""; //void == if(!b)
var c = " "; //blank == if(c) == length
var d = "text"; //there == if(d) == length
var e = true; //true == true == if(e)
var f = false; //false == false == if(!f)
var g = null; //false == if(!g) == !length
var h = 0; //0 == if(!h)
var i = 1; //true == if(i)
var j = 0/0; //NaN == if(!j)
var k = document.body; // == if(k)
var l = document.getElementById("nothing"); // if(!l) == !length
consoletotal(l);
function consoletotal(bb){
consolea(bb);
consoleb(bb);
consolec(bb);
consoled(bb);
consolee(bb);
}
function consolea(bb){
if(bb){
console.log("yes" + bb);
}
}
function consoleb(bb){
if(bb===true){
console.log("true" + bb);
}
}
function consolec(bb){
if(bb===false){
console.log("false" + bb);
}
}
function consoled(bb){
if(!bb){
console.log("no" + bb);
}
}
function consolee(bb){
if(bb.length){
console.log("length" + bb);
}
}