数组 新增 | 替换 | 删除

194 阅读1分钟
    填充数组
    var arr = new Array(3).fill(1) // [1, 1, 1]

    var arr = ['a','b','c','d']
    
    arr.splice(1,1)//['a','c','d']
    删除起始下标为1,长度为1的一个值,len设置的1,如果为0,则数组不变

    arr.splice(1,2)//['a','d']
    删除起始下标为1,长度为2的一个值,len设置的2

    替换 ---- item为替换的值

    arr.splice(1,1,'ttt')//['a','ttt','c','d']
    直接改变原数组,替换起始下标为1,长度为1的一个值为‘ttt’,len设置的1

    arr.splice(1,2,'ttt')//['a','ttt','d']
    替换起始下标为1,长度为2的两个值为‘ttt’,len设置的1

    后面增加
    var myArray = ['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle']
    myArray.push('张三')
    console.log(myArray)  //["Manchester", "London", "Liverpool", "Birmingham", "Leeds", "Carlisle", "张三"]

    删除最后一个 并返回
    myArray.pop()
    console.log(myArray)  //["Manchester", "London", "Liverpool", "Birmingham", "Leeds", "Carlisle"]

    前面新增
    myArray.unshift('Edinburgh');
    console.log(myArray)  //["Edinburgh", "Manchester", "London", "Liverpool", "Birmingham", "Leeds", "Carlisle"]

    删除第一个 并返回
    myArray.shift()
    console.log(myArray)  //["Manchester", "London", "Liverpool", "Birmingham", "Leeds", "Carlisle"]