如何检查 Javascript 中的空值?

新手上路,请多包涵

我正在研究一种在我的表单中检索隐藏输入数组的方法,就像这样

<input type="hidden" value="12:34:00" name="timetemp0">
<input type="hidden" value="14:45:00" name="timetemp1">
<input type="hidden" value="15:12:00" name="timetemp2">
<input type="hidden" value="16:42:12" name="timetemp3">
<input type="hidden" value="16:54:56" name="timetemp4">
<input type="hidden" value="17:03:10" name="timetemp5">

我的 javascript 函数通过使用 getElementsByName(‘timetemp’+i) 单独检索这些

    for (i ; i < counter[0].value; i++)
        {
//finds hidden element by using concatenation of base name plus counter

var timetemp = document.getElementsByName('timetemp'+i);

//if there is a value alert that value to user - this is just for testing purposes at the moment
//because there is only one of timetemp.i then it occupies position 0 in array
            if (timetemp[0].value == null)
            {
                alert ('No value');

            }
            else
            {
                alert (timetemp[0].value);

            }
}

所以应该发生的是它会提醒用户隐藏输入中的值,但如果它遇到没有值的输入,如下所示:

 <input type="hidden" value="" name="timetemp16">

然后它会说“没有价值”

但是 if 函数似乎无法与此一起使用:

我努力了:

  1. (timetemp[0].value == null)
  2. (timetemp[0].value === null)
  3. (timetemp[0].value == undefined)
  4. (timetemp[0].value == '')

它似乎总是默认为 else 子句。

有任何想法吗?

原文由 sqlmole 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 362
2 个回答

评论作为答案:

 if (timetime[0].value)

这是有效的,因为 JS 中的任何变量都可以被评估为布尔值,所以这通常会捕获空的、空的或未定义的东西。

原文由 Richard Dalton 发布,翻译遵循 CC BY-SA 3.0 许可协议

在我看来,用“if(value)”来判断一个值是否为空值并不严格,因为“v?true:false”的结果在v的值为0时为false(0不为空)价值)。您可以使用此功能:

 const isEmptyValue = (value) => {
    if (value === '' || value === null || value === undefined) {
        return true
    } else {
        return false
    }
}

原文由 Jamter 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题