JavaScript数组常用方法整理

2021-02-04  本文已影响0人  October_CanYang

js数组常用方法整理

    let arr = [1,2,3]
    arr.push(4,5,6)
    console.log('arr.push',arr)     // [1,2,3,4,5,6]
    let arr = [1,2,3,4,5,6]
    let del = arr.pop()
    console.log('arr.pop',del)  //6
    console.log('pop',arr)      //[1,2,3,4,5]
    let arr = [1,2,3,4,5,6]
    let del = arr.unshift(-1,-2,-3)
    console.log('length',del)    //length:9
    console.log('arr',arr)      //[-1,-2,-3,1,2,3,4,5,6]
    let arr = [1,2,3,4,5,6]
    let add = arr.shift()
    console.log('length',add)   //  返回删除的元素
    console.log('arr',arr)      //  [2,3,4,5,6]
  ------------------------------------------
    let arrShift = []
    let del = arrShift.shift()
    console.log('del',del)              // undefined
    console.log('arrShift',arrShift)    // []
    let arr = [1,2,3]
    let arr1 = [4,5,6]
    let arr2 = ['a','b','c']
    let arrConcat = []
    console.log(arrConcat.concat(arr,arr1,arr2)) //[1, 2, 3, 4, 5, 6, "a", "b", "c"]
    let arr = [1, 2, 3, 'A', 'B', 'C', "a", "b", "c"]
    let arrJoin = arr.join('/')
    console.log('arr',arr)  // [1, 2, 3, "A", "B", "C", "a", "b", "c"]
    console.log('arrJoin',arrJoin)  // 1/2/3/A/B/C/a/b/c
  -----------------------------------------------------------
若没有用指定字符分割
    let arrJoin1 = arr.join()
    console.log('arrJoin1',arrJoin1)    //1,2,3,A,B,C,a,b,c
    let arr = [1, 2, 3, 'A', 'B', 'C', "a", "b", "c"]
    let arrRes = arr.reverse()
    console.log('arr',arr)  // ["c", "b", "a", "C", "B", "A", 3, 2, 1]
    console.log('arrRes',arrRes)  //  ["c", "b", "a", "C", "B", "A", 3, 2, 1]
    let arr = [8, 5, 3, 'C', 'A', 'B', "g", "f", "e"]
    console.log('arr',arr)  //[3, 5, 8, "A", "B", "C", "e", "f", "g"]
    let arr = [1,2,3,4,5,6,8,9]
    console.log(arr.slice(1,5)) //[3, 4, 5, 6]
    console.log(arr.slice(2))   //[4,5,6,8,9]
    console.log(arr.slice(-3,-1)) //  [6, 8]
    let arr = [1,2,3,4,5,6,8,9]
    console.log(arr.splice(1,5)) //[2, 3, 4, 5, 6]
    console.log(arr.splice(2))   //[9]
    console.log(arr.splice(-3,-1)) //  []
上一篇下一篇

猜你喜欢

热点阅读