为什么以下两个语句的结果不同?
('0' ? 'a' : 'b') /* -> 'a' */
('0' == true ? 'a' : 'b') /* -> 'b' */
Run Code Online (Sandbox Code Playgroud)
编辑:
我应该补充一点,我怀疑'0'第一个语句要转换为boolean来进行比较 - 这应该与"'0'== true"完全相同"显然这不是真的.
今天当我做一些实验时==,我意外地发现了这一点"\n\t\r" == 0.究竟怎么"\n\t\r"等于0,或false?
我做的是:
var txt = "\n"; //new line
txt == 0; //it gives me true
Run Code Online (Sandbox Code Playgroud)
这真让我恼火.所以我做了更多:
var txt = "\r"; //"return"
txt == 0; //true
var txt = "\t"; //"tab"
txt == 0; //true
Run Code Online (Sandbox Code Playgroud)
根本没有意义.怎么会发生?更疯狂的是:
//Checking for variable declared or not
var txt ="\n\t\r";
if(txt!=false){
console.log("Variable is declared.");
}else{
console.log("Variable is not declared.");
}
Run Code Online (Sandbox Code Playgroud)
它给了我什么 Variable is not declared.
怎么等于0,或false???
谈话很便宜,我会展示我的代码.
var a; // a = undefined
if(a == false){ // As I typed == not ===, a needs to be translated to boolean (undefined == false) but it doesn't
return false;
}
else {
return true;
}
// true
Run Code Online (Sandbox Code Playgroud)
这返回true但我确信它会返回false,因为当我使用double equal时,undefined与false相同.
当我尝试使用时,事情变得奇怪
if(!a){..} else {..};
// false
Run Code Online (Sandbox Code Playgroud)
在这里,我得到了我的假,但直到这一刻,我认为(!a)和(a == false)绝对等于.
javascript ×3