【问题标题】:How to slice children array?如何切片儿童数组?
【发布时间】: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.fromvar childs = Array.from(document.getElementById("container").children);
  • children 的结果是 HTMLCollection 不是数组,您可能希望将其更改为 HTMLCollection var childs = Array.from( document.getElementById("container").children )`其余的应该是一样的。另请注意,Array.from 在 IE 上不可用,因此您可能需要一个 polyfill

标签: javascript arrays slice


【解决方案1】:

sliceArray方法,但是可以在Array-like objects上使用:

console.log( [].slice.call(container.children, 2) )

console.log( [].slice.bind(container.children)(2) )

console.log( [].slice.apply(container.children, [2]) )
<div id="container">
  <p> 1 </p>
  <p> 2 </p>
  <p> 3 </p>
  <p> 4 </p>
 </div>

【讨论】:

    【解决方案2】:

    var arr = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"];
    console.log(arr.slice(4))
    
    var childs = Array.from(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>

    【讨论】:

      【解决方案3】:

      是的,DOM 节点不是数组,所以如果你想像这样使用它们,你需要定义你自己的函数来这样做。例如,您可以定义一个切片函数:

      function slice(list, start, end) {
          var result = []
          for (var i = start; i < end; i++) {
              result.push(list[i])
          }
          return result
      }
      

      例如,

      slice(document.getElementById("container").children, 0, 5)
      

      在我看来,这样的“帮助”方法很少应该单独创建,除非您绝对确定您将切片 DOM 节点列表足以节省您的技术负担。对我来说,这些“辅助”函数会带来认知负担,而这只有在 Ramda.js 等更大的框架内才有意义。我的意思是,只要在你正在使用的框架内使用开发中

      您可以尝试查看其中一个功能框架,看看它是否对您有意义。例如,Ramda.js 已经有一个 slice 方法可以对 DOM 节点或任何其他类似数组的对象进行切片:

      R.slice(0, 5, document.getElementById("container").children)
      

      【讨论】:

        【解决方案4】:

        您不能直接删除,因为它们是 Html 元素

        改用这个,或者按照 Md Johirul Islam 的建议做

        document.getElementById("container").removeChild(childs[4])
        

        【讨论】:

        • 这实际上是从 DOM 中删除元素,而不仅仅是“数组”
        • 是的,我明白了。这就是为什么我说按照 Md Johirul Islam 的建议去做或将其从 DOM 中删除