HTML 元素作为 While 条件

HTML Elements as While Conditions

我在学习如何编码时遇到了一些关于我 运行 的代码的问题。

我想知道 HTML 元素如何在 JavaScript while 循环中充当布尔条件。

例如,假设我有一个 HTML table 和一个指向 table:

的 while 循环

HTML Table:

<table border="1" id="menuTable">
    <tr>
        <td align="center">
            <input type="checkbox"/>
        </td>
        <td>Random Data</td>
        <td>More Random Data</td>
    </tr>
</table>

JavaScript 循环:

var Tags = document.getElementsByTagName('INPUT');

var Parent = Tags[0].parentNode; //so Parent should be the <td> tag 

//Here is where things get confusing for me...

function sampleFunction(){
    while (Parent) //How is THIS node a possible boolean condition? What's being evaluated?
    {  
        if (Parent.nodeName == "TR"){
            return Parent;
        }
        Parent = Parent.parentNode;  
    }
    return Parent;
}

//I understand that the while loop is supposed to return a <tr> tag after the loop runs...
//what I don't understand is how the <td> tag/Parent variable can operate as a condition.

希望问题清楚。
一段时间以来,我一直在寻找这个问题的答案。谢谢

while (Parent) //How is THIS node a possible boolean condition? What's being evaluated?

在 JavaScript 中,除了布尔值、整数、字符串、数组和对象之外,还有 2 种棘手的数据类型您需要注意。这是 undefinednull 数据类型。

基本上这个 while (Parent) 正在检查的内容等于:

Parent !== null && Parent !== undefined && Parent !== false

如果此时 Parent 被赋值,这个表达式将计算为 True.

我听说人们将此称为检查 "while Parent exists",因为您可能会在 while 循环中设置一个条件,将 Parent 设置为 undefined 或 null 或 false 以提前终止循环。

所以基本上,当 Parent 存在时,或者当它不存在时 nullundefinedfalse