js遍历函数forEach()、map()、every()和some()的区别实例

forEach()、map()、every()和some()的联系和区别

map()

array.map(function(currentValue,currentIndex,array) {}, this)
// this为执行callback时使用的this值

map() 方法返回一个由原数组中的每个元素执行callback函数后的返回值组成的新数组

let arr = [1, 2, 3, 4, 5]
let add = function(x) {
    return x * x
}
let res = arr.map(add)
console.log(res)
// 输出: [1, 4, 9, 16, 25]

foreach()

array.forEach(function(currentValue,currentIndex,array) {}, this)
// this为执行callback时使用的this值

foreach()方法为原数组中的每个元素执行一次callback函数

let arr = [1, 2, 3, 4, 5]
let add = function(x) {
    console.log(x * x)
}
arr.forEach(add)
// 输出:1 4 9 16 25

every()

array.every(function(currentValue,currentIndex,array) {}, this)
// this为执行callback时使用的this值

every()为数组中的每个元素执行一次callback函数,直到它找到一个返回值为可以转化为布尔值false的值此时every()方法将立刻返回false,否则立刻返回true

let arr1 = [6, 6, 6, 6, 5]
let arr2 = [6, 6, 6, 6, 6]
let comp = function (x) {
    return x > 5
}
console.log('arr1.every():', arr1.every(comp))
console.log('arr2.every():', arr2.every(comp))
// 输出:
// arr1.every(): false
// arr2.every(): true

some()

array.some(function(currentValue,currentIndex,array) {}, this)
// this为执行callback时使用的this值

some()为数组中的每个元素执行一次callback函数,直到它找到一个返回值为可以转化为布尔值true的值,此时some()方法将立刻返回true,否则立刻返回false

let arr1 = [6, 6, 6, 6, 5]
let arr2 = [6, 6, 6, 6, 6]
let arr3 = [5, 5, 5, 5, 5]
let comp = function (x) {
    return x > 5
}
console.log('arr1.some():', arr1.some(comp))
console.log('arr2.some():', arr2.some(comp))
console.log('arr3.some():', arr3.some(comp))

// 输出:
// arr1.some(): true
// arr2.some(): true
// arr3.some(): false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值