JavaScript疯狂的循环(forEach,map,filter,some,every,reduce,reduceRight,find,findIndex,for of)

forEach()

forEach没有返回值。

是一个普通的for循环,写法上比for循环简单,适用于普通的循环

接收三个参数:每个数组的元素,下标index,自身

let a1 = ['hello', 'world']
let b1 = a1.forEach((item, i, arr) => {
  console.log(item, i, arr)
})
console.log(b1) // undefined

map()

map返回一个新数组。

在使用过程中当需要返回一个新的数组时,建议优先使用map,而不是forEach

let a2 = [1, 2, 3]
let b2 = a2.map(v => {
  return v * 2
})
console.log(a) // [1, 2, 3]
console.log(b) // [2, 4, 6]

 filter()

filter返回一个新数组。

返回符合指定要求的数组

let a3 = [
  {
    title: '标题1',
    show: true
  },
  {
    title:'标题2',
    show: false
  },
  {
    title:'标题3',
    show: true
  }
]
let b3 = a3.filter(item => {
  return item.show // 返回show为true的数据
})
console.log(b3)

some()

some返回一个Boolean类型数据。

当数组中其中一个元素满足指定要求即返回true,否则返回false

let a4 = ['yellow', 'red', 'blue']
let b4 = a4.some(v => {
  return v === 'red'
})
console.log(b4) // true

every()

every返回一个Boolean类型的数据。

当数组中所有的元素都满足指定要求即返回true,否则返回false

let a5 = [2, 4, 6, 8]
let b5 = a5.every(v => {
  return v % 2 === 0 // 判断数组中的元素是不是都是偶数
})
console.log(b5) // true

reduce()

reduce可用于计算数组的和

reduceRight()

执行顺序与reduce相反

let a6 = [1, 2, 3, 4, 5, 6 ,7, 8, 9, 10]
/**
 * preTotal:之前值的和
 * currentValue: 当前值
 */
let b6 = a6.reduce((preTotal, currentValue) => {
  console.log(currentValue) /*1, 2 ... 7, 8, 9*/
  return preTotal + currentValue
})
console.log(b6) // 55
let b7 = a6.reduceRight((preTotal, currentValue) => {
  console.log(currentValue) /*9, 8, 7 ... 2, 1**/
  return preTotal + currentValue
})
console.log(b7) //55

find()

find返回通过指定条件(函数内判断)的数组的第一个元素的值。

let a8 = [
  {
    name: 'Tom',
    age: 18
  },
  {
    name: 'Anny',
    age: 15
  },
  {
    name: 'Kobe',
    age: 22
  },
]
let b8 = a8.find((item) => {
  return item.age > 15
})
console.log(b8) // {name: 'Tom', age: 18}

findIndex()

find方法返回通过指定条件(函数内判断)的数组的第一个元素的值。 

let a9 = ['webpack', 'node', 'vue']
let b9 = a9.findIndex(v => {
  return v === 'node'
})
console.log(b9) // 1

for of 

let arr = ['apple', 'banana', 'orange']
for (let val of arr) {
    console.log(val) // 'apple', 'banana', 'orange'
}
for (let index of arr.keys()) {
    console.log(index) // 0 1 2
}
for (let [index, val] of arr.entries()) {
    console.log(index, val) // 0 "apple"  1 "banana" 2 "orange"
}
    

---输出结果

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值