最近发现用到数组方法要去mdn上去翻一下,所以自己总结一下加深印象
reduce()
- 对数组中的每一个元素执行提供的reducer函数,返回一个值
const arr = [1, 2, 3, 4, 5]
const res = arr.reduce((acc, cur) => acc + cur)
const res1 = arr.reduce((acc, cur) => acc -cur, 10)
console.log(res); // 15
console.log(res1); // -5
unshift()
- 在数组的开头添加元素,返回数组的新长度,改变原数组
const arr = [1, 2, 3, 4, 5]
const res = arr.unshift(3)
console.log(arr) // [3,1,2,3,4,5]
push()
- 在数组的末尾添加元素,返回数组的新长度,改变原数组
const arr = [1, 2, 3, 4, 5]
const res = arr.unshift(3)
console.log(arr) // [3,1,2,3,4,5]
pop()
- 从数组中删除最后一个元素,返回该元素的值,改变原数组
const plants = ['broccoli', 'cabbage', 'kale', 'tomato']
console.log(plants.pop()) // "tomato"
console.log(plants) // ["broccoli", "cabbage", "kale"]
shift()
- 从数组中删除第一个元素,并返回这个元素的值,改变原数组
const arr = [1, 2, 3]
const firstElement = arr.shift()
console.log(arr) // [2, 3]
console.log(firstElement) // 1
indexOf()
- 返回在数组中可以找到的给定元素的第一个索引,不存在则返回-1
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']
console.log(beasts.indexOf('bison')) // 1
// start from index 2
console.log(beasts.indexOf('bison', 2)) // 4
console.log(beasts.indexOf('giraffe')) // -1
lastIndexOf()
- 和indexOf()功能差不多,但是是从数组后面向前查找,返回在数组中可以找到的给定元素的最后一个索引。
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']
console.log(animals.lastIndexOf('Dodo')) // 3
const arr = [1,2,3,4,5,2]
console.log(arr.lastIndexOf(2)) // 5
fill()
- 用一个固定值填充数组
const arr = new Array(10).fill(1)
console.log(arr) // [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]