在过去的几年中,JavaScript语言进行了多次更新。为了跟上技术更新的脚步,时刻保持一颗学习的心。趁着休息的时间学习熟悉一下数组的includes
、reduce
的使用。
Array.prototype.includes
ES7添加对此方法的支持,includes()
方法用来判断一个数组是否包含一个指定的值的元素,并返回布尔值true
或false
,如果包含则返回 true
,否则返回 false
。
语法
arr.includes(valueToFind[, fromIndex])
参数
valueToFind
(必须):需要查找的元素值,比较字符串和字符时是区分大小写。fromIndex
(可选):从数组fromIndex
索引处开始查找valueToFind
。- 负数 ,则按升序从
array.length + fromIndex
的索引开始搜 (即使从末尾开始往前跳fromIndex
的绝对值个索引,然后往后搜寻)。 - 默认值为
0
。
- 负数 ,则按升序从
返回值
包含则返回 true
,否则返回 false
。
实例
// ES5 Code
const numbers = ["一", "二", "三", "四"];
console.log(numbers.indexOf("一") > -1); // true
console.log(numbers.indexOf("六") > -1); // false
// ES7 Code
console.log(numbers.includes("一")); // true
console.log(numbers.includes("六")); // false
console.log(numbers.includes("一",1)); // false,从数组索引为`1`往后找
console.log(numbers.includes("一", -3)); // true,从 `array.length + fromIndex` 的索引开始完后找,跟上面从索引为1开始等效
复制代码
使用
includes
方法可以使代码简短易懂。include
方法在比较值时也很方便,如下代码。
// 过去
const day = "星期二";
if (day === "星期二" || day === "星期三" || day === "星期四") {
console.log(day);
}
// 现在
if (["星期二", "星期三", "星期四"].includes(day)) {
console.log(day);
}
复制代码
Array.prototype.reduce
reduce()
方法对数组中的每个元素执行reducer函数(升序执行),将其结果汇总为单个返回值。
语法
Array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
为数组中的每一个元素依次执行callback
函数,不包括数组中被删除或从未被赋值的元素。
参数
callback
(必须):执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的reducer函数,包含四个参数-
accumulator
(必须):累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,初始值可以通过initialValue
定义,默认为数组的第一个元素值,累加器将保留上一个操作的值,就像静态变量一样 -
currentValue
(必须):数组中正在处理的元素 -
index
(可选):数组中正在处理的当前元素的索引。 如果提供了initialValue
,则起始索引号为0
,否则从索引1
起始。注意:如果没有提供
initialValue
,reduce 会从索引1
的地方开始执行callback
方法,跳过第一个索引。如果提供initialValue
,从索引0
开始。 -
array
(可选):调用reduce()
的数组
-
initialValue
(可选):作为第一次调用callback
函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用reduce
将报错。
返回值
函数累计处理的结果。
实例
const arrNumbers = [1, 2, 3, 4, 5];
const reduceNumbers = (arrayNumbers, accumulatorInitVal = false) => {
const reduceCallback = (accumulator, currentVal, currentIndex) => {
console.log(`当前索引:${currentIndex}`);
return accumulator + currentVal;
};
return accumulatorInitVal
? arrayNumbers.reduce(reduceCallback, accumulatorInitVal)
: arrayNumbers.reduce(reduceCallback);
};
console.log(reduceNumbers(arrNumbers)); // 15,累计器初始值为数组的第一个元素的值1
console.log(reduceNumbers(arrNumbers, 10)); // 25,累计器初始值为10
复制代码
console.log(
当前索引:${currentIndex})
,是为了更加直观的看到索引值。
第一次未定义初始值输出如下:
当前索引:1
当前索引:2
当前索引:3
当前索引:4
复制代码
第二次定义了累计器初始值输出如下:
当前索引:0
当前索引:1
当前索引:2
当前索引:3
当前索引:4
复制代码
接下来我们来看一个奇葩需求,出于某种原因,需要一个包含所有用户全名的新数组(他们的姓,加上他们的名字),但只有当他们是20多岁,并且他们的全名是3个字的时候才需要。不要问我们为什么需要这么奇葩的数据子集,产品经理问了,我们很乐意帮忙^_^
const users = [
{
firstName: "坚",
lastName: "孙",
age: 37,
},
{
firstName: "策",
lastName: "孙",
age: 21,
},
{
firstName: "葛亮",
lastName: "诸",
age: 28,
},
{
firstName: "备",
lastName: "刘",
age: 44,
},
{
firstName: "统",
lastName: "庞",
age: 22,
},
{
firstName: "维",
lastName: "姜",
age: 19,
},
{
firstName: "伯温",
lastName: "刘",
age: 22,
},
];
const getFullName = (user) => `${user.lastName}${user.firstName}`;
const filterByAge = (user) => user.age >= 20 && user.age < 30;
// 常规实现
const getFilterResult = users
// 第一步筛选年龄20-30之间的用户
.filter((user) => filterByAge(user))
// 拼接全名
.map((user) => getFullName(user))
// 筛选
.filter((fullName) => fullName.length === 3);
console.log(getFilterResult); // [ '诸葛亮', '刘伯温' ]
// 迭代方式实现
const iterationsFilterResult = (arrayResult, currentUser) => {
const fullname = getFullName(currentUser);
if (filterByAge(currentUser) && fullname.length === 3) {
arrayResult.push(fullname);
}
return arrayResult;
};
console.log(users.reduce(iterationsFilterResult, [])); // [ '诸葛亮', '刘伯温' ]
复制代码