javascript - 如何检查 Javascript 中的空值?

标签 javascript html null

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

<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">

然后它会说“没有值(value)”

但是 if 函数似乎无法处理:

我试过:

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

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

有什么想法吗?

最佳答案

评论作为答案:

if (timetime[0].value)

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

关于javascript - 如何检查 Javascript 中的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6997187/

相关文章:

javascript - 如何在 Javascript 中使用 PHP 中的 JSON 数据(数组)

javascript - jQuery 和 Bootstrap 3 : TypeError: "Object [object HTMLAnchorElement] has no method ' preventDefault'

javascript - Angular ngRoute 导致无限循环和堆栈溢出

javascript - AngularJS 思考 - 在 AJAX 请求中修改 DOM 的正确方法是什么?

php - 如何检索存储在表中的sql查询并为表中的所有查询创建动态php页面

html - 为什么我的图像背景在 float : left? 上消失

javascript - 将参数传递给 React Router 中的 React 元素

java - 以优雅的方式检查两个参数是否为 null

php - 在 PHP 中避免空值时,我可以重新实现 isset 吗?

null - sql联合所有数据类型错误与空值