zoukankan      html  css  js  c++  java
  • 小tips:JS操作数组的slice()与splice()方法

    slice(start, end)

    slice()方法返回从参数指定位置开始到当前数组末尾的所有项。如果有两个参数,该方法返回起始和结束位置之间的项,但不包括结束位置的项。

    var colors = ["red", "green", "blue", "yellow", "purple"];
    var colors2 = colors.slice(1);
    var colors3 = colors.slice(1,4);
    
    console.log(colors2); // green, blue, yellow, purple
    console.log(colors3); // green, blue, yellow

    splice()有删除,插入,替换的功能

    删除需要两个参数,要删除的第一项的位置和要删除的项数。

    var colors = ["red", "green", "blue"];
    var removed = colors.splice(0,1);
    console.log(colors); // greeen, blue
    console.log(removed); // red

    插入需要三个参数:起始位置、0(要删除的项数)和要插入的项

    var colors = ["red", "green", "blue"];
    var removed = colors.splice(1,0,"yellow", "orange");
    console.log(colors); // ["red", "yellow", "orange", "green", "blue"]
    console.log(removed); // 返回空

    替换需要三个参数:起始位置、要删除的项数和要插入的任意数量的项。

    var colors = ["red", "green", "blue"];
    var removed = colors.splice(1,1,"yellow", "orange");
    console.log(colors);  // ["red", "yellow", "orange", "blue"]
    console.log(removed); // ["green"]
  • 相关阅读:
    转:Gerrit 学习
    list, set操作
    Dice chrone execise
    【转】terminal 快捷键
    python package list
    爬虫2
    爬虫 1
    django跨表联查传输数据到前端
    vue实现鼠标移入移出事件
    pycharm意外关闭导致报错Unexpected content storage modification:
  • 原文地址:https://www.cnblogs.com/moqiutao/p/6629104.html
Copyright © 2011-2022 走看看