Array 方法

101 阅读2分钟

Array 操作方法

  1. Array.prototype.find((value) => true)

从数组的开始进行遍历,返回第一个符合要求的值,否则返回undefined

const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}]

array.find((value) => value.v > 3) // {v: 4}
  1. Array.prototype.findIndex((value) => true)

从数组的开始进行遍历,返回第一个符合要求项的索引,否则返回undefined

const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}]

array.findIndex((value) => value.v > 3) // 3
  1. Array.prototype.findLast((value) => true)

从后往前遍历数组,返回第一个符合要求项的值,否则返回undefined

const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}]

array.findIndex((value) => value.v > 3) // {v: 5}

  1. Array.prototype.findLastIndex(() => true)

从后往前遍历,返回第一个符合要求项的索引,否则返回undefined

const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}]

array.findIndex((value) => value.v > 3) // 4

  1. Array.prototype.toReversed()

对数组进行反转,功能参照reversed(),区别是不会改变原数组,会返回一个新的数组

const arr = ['a''b''c'];  
const result = arr.toReversed();  
console.log(result); // ['c', 'b', 'a']  
console.log(arr);    // ['a', 'b', 'c']
  1. Array.prototype.toSorted()

对数组进行排序,和sort功能一样,区别是不改变原数组,会返回一个新的数组

const arr = ['c''a''b'];  
const result = arr.toSorted();  
console.log(result);  // ['a', 'b', 'c']  
console.log(arr);     // ['c', 'a', 'b']

  1. Array.prototype.toSpliced()

对数组进行就修改,功能能参照splice,区别是不会更改原数组,返回一个新的数组

const arr = ['a''b''c''d'];  
const result = arr.toSpliced(12'X');  
console.log(result); // ['a', 'X', 'd']  
console.log(arr);    // ['a', 'b', 'c', 'd']
  1. Array.prototype.with(index, value)

改变数组某一索引对应的值,功能参照[0][0],不改变原数组,返回一个新的数组

const arr = ['a''b''c'];  
const result = arr.with(1'X');  
console.log(result);  // ['a', 'X', 'c']  
console.log(arr);     // ['a', 'b', 'c']
  1. Array.prototype.filter((value) => true)

筛选符合要求的所有项,返回一个数组,没有符合要求的返回一个空数组

const arr = ['a', 'b', 'b', 'a'];
const res = arr.filter((value) => value === 'a')
console.log(res) // ['a', 'a']
  1. Array.prototype.sort()

对数组进行排序,会改变原数组

默认排序是按照字母升序

const a = [1, 2, 40, 5, 46, a, 88]

a.sort()

console.log(a) // [1, 2, 40, 46, 5, 88, 'a']

按照数字进行排序

const a = [1, 2, 3]

a.sort((a, b) => a -b) // 升序
a.sort((a, b) => b -a) // 降序
  1. Array.prototype.reverse()

对数组进行反转

  1. Array.prototype.splice(start, deleteCount, ...items)

对原数组进行删除,添加,更改