ES6数组方法汇总

1.forEach

forEach会遍历数组, 没有返回值, 不允许在循环体内写return, 不会改变原来数组的内容.

const array = [1,2,3,4];

array.forEach((item, index, array) => {

  console.log(item)       // 顺序打出 1 2 3 4

})

2.map

map 遍历数组, 会返回一个新数组, 不会改变原来数组里的内容

const array = [1, 2, 3, 4];

const temp = array.map((item, index, array) => {

  return item

})

console.log(temp)  // [1, 2, 3, 4]

3.filter

filter 会过滤掉数组中不满足条件的元素, 把满足条件的元素放到一个新数组中, 不改变原数组

const array = [1, 2, 3, 4]

const temp = array.filter((item, index, array) => {

  return item >  3

})

console.log(temp)  // [4]

4.every

every遍历数组, 每一项都是true, 则返回true, 只要有一个是false, 就返回false

const array = [1, 2, 3, 4];

const boolen = array.every((item, index, array) => {

  return item > 2

})

console.log(boolen)      // false

5.some

遍历数组的每一项, 有一个返回true, 就停止循环

const array = [1, 2, 3, 4]

const tmep = array.some((item, index, array) => {

  return item > 1

})

console.log(temp)  // true

6.indexOf

查找某个元素的索引值,若有重复的,则返回第一个查到的索引值,若不存在,则返回 -1

const array = [1, 2, 3, 4, 5]

const b = array.indexOf(2)
const c = array.indexOf(6)

console.log(b)      // 1
console.log(c)      // -1

7.find

返回第一个符合条件的数组元素

const array = [1,2,3,4,5,2,4]
const temp = array.find((value, index, array) => value > 2)
console.log(temp)   // 3

8.findIndex

返回第一个符合条件的数组元素索引值

const array = [1,2,3,4,5]
const temp = array.findIndex((value, index, array) => value > 3)
console.log(temp)  // 3

总结的这些都算是自己比较常用的方法,如有疑问请提出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值