js中firstChild和childNodes[0]以及children[0]之间的点滴问题

本文探讨了JavaScript中firstChild、childNodes[0]和children[0]在获取元素第一个子节点时的区别。在包含换行的情况下,firstChild和childNodes[0]会将换行视为文本节点,而children[0]则忽略文本节点,直接获取HTML元素节点。去除换行后,三种方法都能正确获取第一个元素节点。需要注意,children属性虽方便但并不标准,标准方法为firstChild和childNodes。

示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>js中firstChild和childNodes[0]以及children[0]之间的点滴问题</title>
	</head>
	<body>
		<div id="div1">
			<p>
				pppppppppppppppp
			</p>
		</div>
		<script type="text/javascript">
			window.onload = function() {
				if (!document.getElementById("div1")) return false;
				var div1 = document.getElementById("div1");
				console.log(div1.firstChild);
				console.log(div1.firstChild.nodeType);
				
				console.log(div1.childNodes[0]);
				console.log(div1.childNodes[0].nodeType);
				
				console.log(div1.children[0]);
				console.log(div1.children[0].nodeType);
				
				console.log(document.getElementsByTagName("p")[0].firstChild.nodeValue);
			};
		</script>
	</body>
</html>

运行结果入下:


分析:

### 关于二叉树中 \( n_0 \) 的定义及其应用 \( n_0 \) 表示的是二叉树中度为 0 的节点数量,即叶子节点的数量[^2]。这些节点没有子节点,在实际的应用场景中通常用于终止条件或者作为数据存储单元。 #### 度为 0 节点的特点 在任何二叉树中,度为 0 的节点不会有任何孩子节点。这意味着它们只负责保存信息而不参与进一步的分支扩展。这种特性使得 \( n_0 \) 成为了衡量二叉树规模的一个重要指标之一。 #### 数学关系 对于任意非空二叉树而言,存在一种固定的关系:如果该二叉树中有 \( n_2 \) 个度为 2 的节点,则必然有 \( n_0 = n_2 + 1 \)[^2]。这一规律揭示了不同类型的节点之间紧密联系,并提供了计算某些特定参数的有效方法。 以下是基于上述理论实现的一段简单验证程序: ```c #include <stdio.h> #include <stdlib.h> #define MAX_TREE_SIZE 100 typedef int ElemType; // 定义结点结构体 typedef struct CSNode { ElemType data; struct CSNode* firstchild; struct CSNode* rightsib; } CSNode, *CSTree; int countN0(CSNode* root){ if(root == NULL) return 0; if(root->firstchild==NULL && root->rightsib==NULL) return 1;// 叶子节点计数 return countN0(root->firstchild)+countN0(root->rightsib); } void main(){ CSTree tree=(CSTree)calloc(1,sizeof(CSNode)); printf("Number of degree zero nodes:%d",countN0(tree)); // 输出n0值 } ``` 此代码片段展示了如何通过递归方式统计给定二叉树中的所有叶节点数目(即 \( n_0 \))。注意这里简化处理仅作示范用途。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值