javascript - 对象中的 null 和 undefined

标签 javascript null undefined

这是我的代码:

<body>
     <p id="x"></p>
     <p id="y"></p>
    <form action="2.php" method="post" name="frm">
        <input type="text" name="srch">
    </form>
    <script>
        obj = document.forms["frm"]["srch7"];
        obj1 = document.getElementById("noexist");
        document.getElementById("x").innerHTML = obj;
        document.getElementById("y").innerHTML = obj1;
    </script>
</body>

为什么obj返回undefined而obj1返回null, document.forms["frm"]["srch7"];和 document.getElementById("不存在");两者都是对象,必须返回 null,因为元素不存在。

最佳答案

两种情况不同,

obj = document.forms["frm"]["srch7"];
//Here you are trying to access a property that 
// is not present under document.forms.frm.

obj1 = document.getElementById("noexist");
//Here it is returning null because getElementById implemented in that way.
// getElementById will return null if the DOM search didn't find any element
// based on the supplied id.

关于javascript - 对象中的 null 和 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37046913/

相关文章:

javascript - 如何在 socket.io 中锁定全局数组

javascript - 如何将填充作为可以单击以触发事件的 div 的一部分

php - $.getJSON 返回未定义的结果

c++ - 空流,我必须包括 ostream 吗?

javascript - 按值对数组的复杂数组进行排序

javascript - 令人困惑的未捕获类型错误 : Cannot read property 'n' of undefined only happens when JSON result has a single item, 为什么?

javascript - 动态添加按钮,同时动态添加文本框 AngularJS

javascript - Ember 中的观察者功能?

php - mysqli 准备好的语句,使用绑定(bind)参数插入 NULL

core-data - CoreData可选的多对多关系永远不会为零?