【发布时间】:2025-12-06 07:55:02
【问题描述】:
在此示例中,我首先对数组进行切片。那行得通。然后我尝试对一个用 .children 制作的数组进行切片,但它没有用。在这样的例子中,我怎样才能得到一半的孩子?
var arr = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"];
console.log(arr.slice(4))
var childs = document.getElementById("container").children;
console.log(childs)
console.log(childs.slice(4));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<p>unaffected</p>
<p>unaffected</p>
<p>unaffected</p>
<p>unaffected</p>
<p>affected</p>
<p>affected</p>
<p>affected</p>
<p>affected</p>
</div>
【问题讨论】:
-
Dom 节点不是数组,有一个集合。但你可以先使用
Array.from。var childs = Array.from(document.getElementById("container").children); -
children的结果是HTMLCollection不是数组,您可能希望将其更改为HTMLCollectionvar childs = Array.from( document.getElementById("container").children )`其余的应该是一样的。另请注意,Array.from在 IE 上不可用,因此您可能需要一个 polyfill
标签: javascript arrays slice