gpt4 book ai didi

Javascript - 从数组中删除子元素或父元素

转载 作者:行者123 更新时间:2023-11-29 15:14:29 25 4
gpt4 key购买 nike

我得到了一个代码,用于从可能同时包含子元素和父元素的随机数组中删除子/父元素,例如:

<html>

<body>
<div id='1'>
<div id='2'>
<div id='3'>
</div>
<div id='4'>
</div>
</div>
</div>
<div id='5'>
<div id='6'>
</div>
</div>
</body>

</html>

arr = document.getElementsByTagName('div')
// arr: [<div#1>,<div#2>, <div#3>, <div#4>, <div#5>, <div#6>]

那么从这个例子中我如何提取 children :

// arr: [<div#3>, <div#4><div#6>]

或者提取 parent :

// arr: [<div#1>, <div#5>]

目前我正在使用:

function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}

function filterArray(arr, parent=true){
newArr = [];
arr.forEach((a)=>{
bool = true

if (parent){
arr.forEach((b)=>{
if (isDescendant(a, b)){
bool = false
};
});
}
else{
arr.forEach((b)=>{
if (isDescendant(b, a)){
bool = false
};
});
}

if(bool){
newArr.push(a)
}
});
return newArr
};

但我很确定会有更好、更高效的解决方案。有更好的解决方案吗?

最佳答案

数组有一个名为 filter 的方法它可以让你做到这一点;过滤数组。要查找一个节点是另一个节点的父节点还是子节点,您可以使用 contains -method(请注意,这可能会在检查节点是否包含自身时返回 true),或者更通用的 compareDocumentPosition -方法。

const nodes = Array.from(document.body.querySelectorAll("div"));

//The most straight-forward way to find the parents,
//filter out any nodes where no other node in the array contains it
//(note the m !== n check, which prevents contains to return true for the same node):
let parents = nodes.filter( n => !nodes.find( m => m !== n && m.contains(n) ));
//Conversely, to find any child-nodes, invert the contains-check to find any nodes that does not contain any other node in the array:
let children = nodes.filter( n => !nodes.find( m => m !== n && n.contains(m) ));
console.log("approach 1:\n", parents, "\n", children);

//Here is the same approach using compareDocumentPosition instead of contains:
parents = nodes.filter( n => !nodes.find(m => m.compareDocumentPosition(n) & Node.DOCUMENT_POSITION_CONTAINED_BY) );
children = nodes.filter( n => !nodes.find(m => n.compareDocumentPosition(m) & Node.DOCUMENT_POSITION_CONTAINED_BY) )

console.log("approach 2:\n", parents, "\n", children);

//And finally, if you don't need the restriction of checking against
//elements in the array, you can just see if the nodes have
//the topmost parent/any children at all:
const topElement = document.body;
parents = nodes.filter( n => n.parentElement === topElement );
children = nodes.filter( n => !n.childElementCount );
console.log("approach 3:\n", parents, "\n", children);
<div id='1'>
<div id='2'>
<div id='3'>
</div>
<div id='4'>
</div>
</div>
</div>
<div id='5'>
<div id='6'>
</div>
</div>

快速基准显示最后一种方法是最快的(至少在我的机器上)(毫不奇怪,它不必多次搜索数组),然后是 contains-version .最慢的是使用 compareDocumentPosition,但这仍然比运行 filterArray 来获取子数组要快。

关于Javascript - 从数组中删除子元素或父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50572172/

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