数组方法

54 阅读2分钟

toString() 返回字符串

  • 只能是逗号分隔,不可指定
  • 数组转字符串方法
[1,2,3].toString('???') // '1,2,3'

join('指定字符') 返回字符串

  • 可指定字符
  • 无参数就是逗号
[1,2,3].join('?') // '1?2?3'

slice(startIndex,endIndex) 剪切数组,返回新数组

  • 原数组不变
  • 第二个参数没有,剪切所有剩余
  • 第二个参数为负数,从尾部切掉几个
  • 不包括endIndex
  • 剪切个数为endIndex-startIndex
const arr = [1,2,3,4,5,6]
console.log(arr.slice(1,2)) // [2]
console.log(arr.slice(1)) // [2, 3, 4, 5, 6]
console.log(arr.slice(1,-2)) //  [2, 3, 4]

splice(startIndex,deleteCount,item1,item2...) 返回数组

  • 原数组改变
  • 参数1开始索引,删除个数,item是从startIndex位置加入的新元素
  • 返回删掉的数组
const arr = [1, 2, 3, 4]
console.log(arr.splice(1, 2, "?", "!")) // [2,3] 
console.log(arr) // [1, '?', '!', 4]

indexOf(item)/lastIndexOf(item) 返回索引

  • 找不到返回-1
const b = [1, 2, 2, 3]
console.log(b.lastIndexOf(2)) // 1
console.log(b.indexOf(2)) // 1

concat(arr) 返回新数组

  • 原数组不变
const a = [1, 2]
console.log(a.concat([4, 5])) [1,2,4,5]
console.log(a) // [1,2]

push(item) 尾部追加

  • 原数组改变
const arr = [1, 2]
console.log(arr.push(3)) // 3
console.log(arr) // [1,2,3]

pop() 尾部弹出删除,返回弹出项

  • 原数组改变
const arr = [1, 2]
console.log(arr.pop()) // 2
console.log(arr) // [1]

unshift(item) 头部追加

  • 原数组改变
let arr = [1,2]
console.log(arr.unshift(3)) // 3
console.log(arr) // [3,1,2]

shift() 头部删除,返回删除项

  • 原数组改变
const arr = [1,2,4]
console.log(arr.shift()) // 1
console.log(arr) // [2,4]

reverse() 反转数组

  • 原数组改变
const arr = [1, 3, 4]
console.log(arr.reverse()) // [4, 3, 1]
console.log(arr) // [4, 3, 1]

includes(item,startSearchIndex) 返回布尔

  • 是否包括某项
  • 第二个参数为开始搜索位置,包括这个位置
console.log([1, 2, 3, 4].includes(2, 2)) // false

sort(fn) 排序

  • 返回大于0表示交换位置
  • 等于小于0表示不交换位置
  • 字母根据字母顺序进行大小判断
const arr = [2, 1, 3]
arr.sort(function (a, b) {
    return a - b // 大于0交换位置
})
console.log(arr) // [1,2,3]
const arr2 = ["c", "a", "b"]
  arr2.sort((a, b) => {
    if (a > b) {
      return 1
    } else {
      return -1
    }
  })
console.log(arr2) // [a,b,c]
const arr3 = [
    { name: "a", age: 30 },
    { name: "b", age: 10 },
    { name: "c", age: 20 },
]
arr3.sort((a, b) => {
    return a.age - b.age
})
console.log(arr3) // 根据age值升序排序

遍历方法:map(fn)

创建一个新的数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果

遍历方法:filter(fn)

创建一个新的数组,其包含通过所提供函数实现的测试的所有元素。

遍历方法:reduce(fn, initialValue)

对数组中的所有元素调用指定的回调函数。该回调函数的返回值是累计结果,并且此返回值在下次调用该回调函数时作为参数提供。