Javascript:为什么不 "if( element != '' ||元素!= null)”工作?

标签 javascript

我的脚本中有这段代码

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/

相关文章:

javascript - Android JQuery focus() 解决方法

javascript - 在 dd/mm/yyyy hh :mm:ss format 中转换日期对象

javascript - 用javascript改变div css

javascript - XHR加载视频

javascript - 如何在Javascript上打开手机浏览器?

javascript - 在 ngFor 循环内显示来自 source.unsplash.com 的 10 张独特图片

javascript - 需要使用 JQuery 和 Shopify 创建集合并使用返回的 ID 添加产品的示例

javascript - 通过过滤未定义计算对象数组的平均值

javascript - 是否有一个 GruntJS 任务可以从源代码模板构建 JS 闭包?

javascript - HTML/JS/CSS 中的 URL 标签列表