gpt4 book ai didi

javascript - HTML 元素作为 While 条件

转载 作者:行者123 更新时间:2023-12-03 09:10:25 24 4
gpt4 key购买 nike

我对学习如何编码时遇到的一些代码有疑问。

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

例如,假设我有一个 HTML 表和一个指向该表的 while 循环:

HTML 表格:

<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)//这个节点如何成为可能的 boolean 条件?正在评估什么?

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

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

父级 !== null && 父级 !== 未定义 && 父级 !== false

如果此时为 Parent 分配了任何值,则该表达式的计算结果将为 True

我听说人们将此称为检查“while Parent 存在”,因为您可能会在 while 循环中设置一个条件,将 Parent 设置为未定义或 null或 false 提前终止循环。

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

关于javascript - HTML 元素作为 While 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32086149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com