JS-数组总结

143 阅读5分钟

创建数组

字面量方式

const arr = [1, 3, 5]

对象构造器

const arr1 = new Array()		// []
// 只有一个参数时表示的是的元素个数
const arr2 = new Array(3)		// [ , , ]
const arr3 = new Array(1, 3, 5)	// [1, 3, 5]
// 不使用new也毫无影响
const arr4 = Array(1, 3, 5)		// [1, 3, 5]

ES6 新增

// 解决对象构造器因为参数个数而产生的问题
const arr1 = Array.of(3)		// [3]
const arr2 = Array.of(1, 3, 5)	// [1, 3, 5]

// 把类数组对象转换为真正的数组
const arr3 = Array.from('135'); // ['1', '3', '5']
const arr4 = Array.from(new Set([1, 3, 5])) // [1, 3, 5]

常用方法

纯函数

join()

// separator(可选):指定使用的分隔符,可以为字符串,默认为逗号
array.join(separator)

将数组中的所有元素通过指定的分隔符进行连接,返回一个字符串

const arr =  ['a', 'b', 'c', 'd']

console.log(arr.join(123))	// a123b123c123d
console.log(arr.join('-'))	// a-b-c-d

slice()

选择一部分元素浅拷贝到一个新的数组中

// start(必须):开始下标,为负数表示从末尾开始
// end(可选):结束下标
array.slice(start, end)
const arr =  ['a', 'b', 'c', 'd']

console.log(arr.slice(1))		// ['b', 'c', 'd']
console.log(arr.slice(-2))		// ['c', 'd']
console.log(arr.slice(1, 2)) 	// ['b']
console.log(arr)			   // ['a', 'b', 'c', 'd']
// 浅拷贝栗子
const arr =  [
  {id: 1,name: 'wly'},
  {id: 2,name: 'tom'}
]

const newArr = arr.slice(1)
console.log(newArr[0]===arr[1])	// true

cancat()

合并两个或多个数组,返回一个新数组

array.cancat(arr1, arr2, ...)
const arr1 =  ['a', 'b']
const arr2 = [1, 2, 3]
const arr3 = ['hello', 'world']

console.log(arr1.concat(arr2, arr3)) // ['a', 'b', 1, 2, 3, 'hello', 'world']
console.log(arr1)	// ['a', 'b']

indexOf()

查找数组中是否存在某个元素,返回元素的下标,不存在则返回 -1

// searchValue(必须):查找的值
// fromIndex(可选):从哪个位置开始查找
array.indexOf(searchValue, fromIndex)
const arr =  ['a', 'b', 'c']
console.log(arr.indexOf('b'))	// 1
console.log(arr.indexOf('d'))	// -1

lastIndexOf()

从后向前查找数组中是否存在某个元素,返回元素的下标,不存在则返回 -1

// searchValue(必须):查找的值
// fromIndex(可选):从哪个位置开始查找
array.indexOf(searchValue, fromIndex)
const arr = ['a', 'b', 'c', 'b', 'e']

console.log(arr.lastIndexOf('b'))	// 3
console.log(arr.lastIndexOf('d'))	// -1

includes()

查找数组中是否包含某个元素,返回布尔值

// searchValue(必须):查找的值
// fromIndex(可选):从哪个位置开始查找
array.includes(searchValue, fromIndex)
const arr = ['a', 'b', 'c']

console.log(arr.includes('b'))	// true
console.log(arr.includes('d'))	// false

非纯函数

sort()

对数组元素进行排序,并返回排序后的数组

// 函数(可选):自定义的排序规则
array.sort(function(a, b))
  • 如果比较函数返回值 <0,则 a 排到 b 的前面
  • 如果比较函数返回值 =0,则 a 和 b 的相对位置不变
  • 如果比较函数返回值 >0,则 b 排在 a 的前面
const arr1 = [2, 1, 3, 1]
const arr2 = ['b', 'a', 'c', 'a']

console.log(arr1.sort()) // [1, 1, 2, 3]
console.log(arr2.sort()) // ['a', 'a', 'b', 'c']
// 举个栗子:将age降序排序,age相同时按照score降序排序
const arr = [
  {age: 25, score: 5},
  {age: 10, score: 20},
  {age: 30, score: 10},
  {age: 5, score: 90},
  {age: 10, score: 40},
]

arr.sort((a, b)=>{
  if(a.age === b.age) {
    return b.score - a.score
  }else {
    return b.age - a.age
  }
})

console.log(arr)

image-20210613150335974.png

splice()

添加、删除、修改数组中的元素

// index(必须):一个整数,表示处理的位置,如果是负数表示从数组末尾开始
// howmany(可选):表示删除的个数,为0时不删除
// item(可选):添加的新元素
array.splice(index, howmany, item1, item2 ...)
// 添加
const arr = [1, 2, 3, 4, 5]

console.log(arr.splice(2, 0, 'a', 'b'))	// []
console.log(arr)	// [1, 2, 'a', 'b', 3, 4, 5]
// 删除
const arr = [1, 2, 3, 4, 5]

console.log(arr.splice(0, 3))	// [1, 2, 3]
console.log(arr)	// [4, 5]
// 修改 
const arr = [1, 2, 3, 4, 5]

console.log(arr.splice(2, 1, 'a'))	// [3]
console.log(arr)	// [1, 2, 'a', 4, 5]
// 似乎这样更直接:arr[2]='a'

pop()

删除数组中的最后一个元素,返回该元素

const arr = ['a', 'b', 'c']

console.log(arr.pop())	// c
console.log(arr)	// ['a', 'b']

shift()

删除数组中的第一个元素,返回该元素

push()

向数组的末尾添加元素,返回新数组的长度

array.push(item1, item2, ...)
const arr = ['a', 'b', 'c']

console.log(arr.push('d', 'e')) // 5
console.log(arr)	// ['a', 'b', 'c', 'd', 'e']

unshift()

向数组的开头添加元素,返回新数组的长度

array.unshift(item1, item2, ...)
const arr = ['a', 'b', 'c']

console.log(arr.unshift('d', 'e')) // 5
console.log(arr)	// ['d', 'e', 'a', 'b', 'c']

unshift()

颠倒数组中元素的顺序

const arr = ['a', 'b', 'c']

console.log(arr.reverse())	// ['c', 'b', 'a']
console.log(arr)	// ['c', 'b', 'a']

遍历数组

以下函数都不会改变原数组

foreach()

依次为数组中的元素执行一次回调函数

// currentValue(必须):当前元素的值
// index(可选):当前元素的索引
// arr(可选):数组对象本身
// thisValue(可选):对象作为该执行回调时使用,传递给函数,用作this的值
array.forEach(function(currentValue, index, arr), thisValue)
const arr = [1, 2, 3, 4, 5]

arr.forEach((item, index)=>{
  console.log(item, index)
})

注意:

foreach() 无法退出循环(即时可以通过抛出异常的方式退出也不建议使用)

如果非要退出循环,请不要使用它

every()

判断数组中的所有元素是否都满足回调函数定义的条件,都满足则返回 true,否则返回 false

array.every(function(currentValue, index, arr), thisValue)

some()

判断数组中的所有元素是否有一个满足回调函数定义的条件,都满足则返回 true,否则返回 false

array.some(function(currentValue, index, arr), thisValue)

find()

查找第一个满足回调函数的元素,并返回该元素,没有则返回 undefined

array.find(function(currentValue, index, arr), thisArg)

findIndex()

查找第一个满足回调函数的元素,并返回该元素的下标,没有则返回 -1

array.findIndex(function(currentValue, index, arr), thisArg)

filter()

通过回调函数进行过滤返回一个新数组

array.filter(function(currentValue,index,arr), thisValue)
const arr = [1, 2, 5, 6]

let newVal = arr.filter((i) => i > 3)

console.log(arr) // [1, 2, 5, 6]
console.log(newVal) // [5, 6]

map()

通过回调函数处理数组中的每一个元素,把回调函数中返回的元素组成一个新的数组返回

array.map(function(currentValue,index,arr), thisValue)
const arr = [1, 2, 5, 6]

let newVal = arr.map((i) => i * i)

console.log(arr) // [1, 2, 5, 6]
console.log(newVal) // [1, 4, 25, 36]

reduce()

接收一个函数作为累加器,依次把上一次函数处理后的返回值作为下一次函数的参数进行处理,最终返回一个值

// total(必须):初始值或上一次函数调用后的返回值
// currentValue(必须):当前元素的值
// index(可选):当前元素的索引值
// arr(可选):数组对象本身
// initialValue(可选):指定第一次回调函数的第一个参数
array.reduce(function(total, currentValue, index, arr), initialValue)
let arr = [1, 2, 5, 6]

let newVal = arr.reduce((total, item) => {
    console.log(total, item)	    /*
									1 2
									3 5
									8 6
								*/
    return total + item
})

console.log(arr)	// [1, 2, 5, 6]
console.log(newVal)	// 14

链式调用

const arr = [1, 2, 5, 6]

let newVal = arr
                .map(i=>i*3)
                .filter(i=>i>5)
                .reduce((total, i)=> total+i)
console.log(newVal) // 39

参考

数组详细操作方法及解析合集