"## [js] 写一个方法获取页面中所有类型的节点数
/**
* 获取页面中所有类型的节点数
* @returns {Object} 返回一个包含节点类型及数量的对象
*/
function getAllNodeTypes() {
const nodes = document.querySelectorAll(\"*\"); // 获取页面中所有节点
const nodeTypes = {}; // 存储节点类型及数量的对象
// 遍历所有节点
nodes.forEach(node => {
const nodeType = node.nodeName; // 获取节点类型
// 如果节点类型已存在,则数量加1;否则,初始化数量为1
if (nodeTypes[nodeType]) {
nodeTypes[nodeType]++;
} else {
nodeTypes[nodeType] = 1;
}
});
return nodeTypes;
}
// 调用方法并打印结果
console.log(getAllNodeTypes());
答案
/**
* 获取页面中所有类型的节点数
* @returns {Object} 返回一个包含节点类型及数量的对象
*/
function getAllNodeTypes() {
const nodes = document.querySelectorAll(\"*\");
const nodeTypes = {};
nodes.forEach(node => {
const nodeType = node.nodeName;
if (nodeTypes[nodeType]) {
nodeTypes[nodeType]++;
} else {
nodeTypes[nodeType] = 1;
}
});
return nodeTypes;
}
console.log(getAllNodeTypes());
以上是一个用于获取页面中所有类型的节点数的 JavaScript 方法。它通过使用 document.querySelectorAll(\"*\") 来获取页面中的所有节点,然后遍历每个节点,统计每种节点类型的数量,并将结果存储在一个对象中返回。通过调用 getAllNodeTypes() 方法,我们可以获取到一个包含节点类型及其数量的对象。
请注意,这里的代码假定你在浏览器环境中运行,并且需要在页面加载完成后调用该方法才能正确获取到页面中的节点。
希望以上代码能够满足你的需求,如果有任何问题,请随时提问。"