我的脚本中有这段代码
var therow;
var rowtitle = ['Name', 'Weight'];
for(var i=0;i<7;i++) {
therow = prompt(rowtitle[i]);
if(therow != '' || therow != null) {
//some code
} else {
//more code
}
therow = null;
}
循环工作正常,提示也工作。问题是
if(therow != '' || therow != null)
我知道这是因为我试过
if(therow != '')
和
if(therow != null)
...独立,并且他们的行为符合预期。
为什么当我将以上两个组合在一个 if 语句中时它什么都不做?
上面的代码有问题吗?
最佳答案
因为它永远是真的。
您已经说过 if it's not a blank string OR it's not NULL
。当它为 NULL 时,它不是空字符串(所以它是真的)。当它是一个空字符串时,它不是 NULL(所以它是真的)。
您想要的是 if (therow != '' && therow != null)
或者更可能是 if (therow)
。我还看到了 if (!!therow)
,它强制它成为一个实际的 bool 值。
关于Javascript:为什么不 "if( element != '' ||元素!= null)”工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18402214/