本文介绍了map、filter、reduce、find、some、every的用法及实现原理。
1、map
map()方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。
用法:
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
实现:
Array.prototype.map = function(fn) {
const arr = [];
for (let item of this) {
arr.push(fn(item));
}
return arr;
}
2、filter
filter()方法创建一个新数组,其包含通过所提供函数实现的测试的所有元素。
用法:
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
实现:
Array.prototype.filter = function(fn) {
const arr = [];
for (let item of this) {
if (fn(item) {
arr.push(item);
}
}
return arr;
}
3、reduce
reduce方法对数组中的每个元素按序执行一个由您提供的reducer函数,每一次运行 reducer会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
用法:
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(previousValue, currentValue) => previousValue + currentValue,
initialValue
);
console.log(sumWithInitial);
// expected output: 10
实现:
Array.prototype.reduce = function(reducer, initialValue) {
let index;
if (initialValue === void 0) {
initialValue = this[0]
index = 1;
} else {
index = 0;
}
for (; index < this.length; index++) {
initialValue = reducer(initialValue, this[index], index, this);
}
return initialValue;
}
4、find find()方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
用法:
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
实现:
Array.prototype.find = function(fn) {
for (let item of this) {
if (fn(item)) return item;
}
}
5、some
方法测试数组中是不是至少有 1 个元素通过了被提供的函数测试。它返回的是一个 Boolean 类型的值。
用法:
const array = [1, 2, 3, 4, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// expected output: true
实现:
Array.prototype.some = function(fn) {
for (let item of this) {
if (fn(item)) return true;
}
return false;
}
6、every
every方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。
用法:
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
实现:
Array.prototype.every = function(fn) {
for (let item of this) {
if (!fn(item)) return false;
}
return true;
}