zoukankan      html  css  js  c++  java
  • js splice()方法

    splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。
    注释:该方法会改变原始数组。

    实例

    例子 1
    在本例中,我们将创建一个新数组,并向其添加一个元素:
    <script type="text/javascript">
    
    var arr = new Array(6)
    arr[0] = "George"
    arr[1] = "John"
    arr[2] = "Thomas"
    arr[3] = "James"
    arr[4] = "Adrew"
    arr[5] = "Martin"
    
    document.write(arr + "<br />")
    arr.splice(2,0,"William")
    document.write(arr + "<br />")
    
    </script>
    输出:
    George,John,Thomas,James,Adrew,Martin
    George,John,William,Thomas,James,Adrew,Martin
    例子 2
    在本例中我们将删除位于 index 2 的元素,并添加一个新元素来替代被删除的元素:
    <script type="text/javascript">
    
    var arr = new Array(6)
    arr[0] = "George"
    arr[1] = "John"
    arr[2] = "Thomas"
    arr[3] = "James"
    arr[4] = "Adrew"
    arr[5] = "Martin"
    
    document.write(arr + "<br />")
    arr.splice(2,1,"William")
    document.write(arr)
    
    </script>
    输出:
    George,John,Thomas,James,Adrew,Martin
    George,John,William,James,Adrew,Martin
    例子 3
    在本例中我们将删除从 index 2 ("Thomas") 开始的三个元素,并添加一个新元素 ("William") 来替代被删除的元素:
    <script type="text/javascript">
    
    var arr = new Array(6)
    arr[0] = "George"
    arr[1] = "John"
    arr[2] = "Thomas"
    arr[3] = "James"
    arr[4] = "Adrew"
    arr[5] = "Martin"
    
    document.write(arr + "<br />")
    arr.splice(2,3,"William")
    document.write(arr)
    
    </script>
    输出:
    George,John,Thomas,James,Adrew,Martin
    George,John,William,Martin
  • 相关阅读:
    POJ-2096-Collecting Bugs(概率DP)
    2019ICPC南京网络赛总结
    LOJ-6285-数列分块入门9
    LOJ-6284-数列分块入门8
    LOJ-6283-数列分块7
    bzoj2049: [Sdoi2008]Cave 洞穴勘测
    bzoj1010: [HNOI2008]玩具装箱toy
    bzoj1597: [Usaco2008 Mar]土地购买
    bzoj1233: [Usaco2009Open]干草堆tower 单调队列优化dp
    bzoj2442&&codevs4654 单调队列优化dp
  • 原文地址:https://www.cnblogs.com/mr-wuxiansheng/p/6622820.html
Copyright © 2011-2022 走看看