Array数组常用方法总结

最近发现用到数组方法要去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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值