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