for循环的方法各式各样, 在不同的情况下, 使用最合适的方法才能事半功倍, 下面总结下各类for循环方法的特点和异同,面对不同的情况时,尽量选择最优方法。
1. filter方法
filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素
返回值: 一个新的、由通过测试的元素组成的数组,如果没有任何数组元素通过测试,则返回空数组。
filter 不会改变原数组,它返回过滤后的新数组
语法: let newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
// 最简单例子
let words = ['first', 'banana', 'chinese', 'challenge', 'render'];
words = words.filter(el => el.length> 5); // ["banana", "chinese", "challenge", "render"]
// 例子2:
const fruits = ["apple", "banana", "grapes", "mango", "orange"];
function filterItems(arr, query) {
return arr.filter((el) => {
return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
});
}
filterItems(fruits, "ap"); // ['apple', 'grapes']
filterItems(fruits, "an"); // ['banana', 'mango', 'orange']
// 例子3
// 以下示例使用 filter() 创建具有非零 id 的元素的 json
let arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{},
{ id: null },
{ id: NaN },
{ id: "undefined" }
];
function filterItems(arr) {
return arr.filter(el => {
return (
el.id !== "undefined" &&
el.id !== null &&
typeof el.id === "number" &&
!isNaN(el.id) &&
el.id !== 0
);
});
};
filterItems(arr) // [{id: 15}, {id: -1}, {id: 3}, {id: 12.2}]
2. reduce() 方法
reduce()方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
reducer 函数接收4个参数:
Accumulator (acc) (累计器)
Current Value (cur) (当前值)
Current Index (idx) (当前索引)
Source Array (src) (源数组)
initialValue可选
作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。
语法: arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
// 例子1 数组里所有值的和
let sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, 0); // 6
// 例子2 累加对象数组里的值
let initialValue = 2;
let sum = [{ x: 11 }, { x: 2 }, { x: 3 }].reduce(function(
accumulator,
currentValue
) {
return accumulator + currentValue.x;
},
initialValue); // 18
3. map()方法
map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
// 例子1 使用一个包含一个参数的函数来mapping(构建)一个数字数组
let numbers = [1, 4, 9];
let doubles = numbers.map(num => num * 2);
console.log(numbers); // numbers数组未被修改: [1, 4, 9]
console.log(doubles); // doubles数组的值为: [2, 8, 18]
// 例子2 使用 map 重新格式化数组中的对象
let arr = [
{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 }
];
let reformattedArray = arr.map((item) => {
let obj = {};
obj[item.key] = item.value;
return obj;
}); // [{1: 10}, {2: 20}, {3: 30}]