深入解析JS中数组reduce方法(附代码)
时间:2021-08-31
来源:互联网
标签:
今天PHP爱好者给大家带来JS中数组reduce代码分享,之前的文章《浅谈Vue中key取值影响过渡效果和动画效果(代码详解)》中,给大家了解一下Vue中key取值影响过渡效果和动画效果。下面本篇给大家了解一下JS中数组reduce方法,有一定的参考价值,有需要的朋友可以参考一下。希望对大家有所帮助。
含义
reduce()
方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值。
语法
arr.reduce(callback[, initialValue])
参数
callback
执行数组中每个值的函数,包含四个参数:accumulator
累加器累加回调的返回值;它是上一次调用回调时返回的累积值,或initialValue
(如下所示)。
currentValue
数组中正在处理的元素。currentIndex
可选
数组中正在处理的当前元素的索引。 如果提供了initialValue
,则索引号为 0
,否则为索引为 1
。array可选
调用reduce
的数组initialValue
可选
用作第一个调用callback
的第一个参数的值。如果没有提供初始值,则将使用数组中的第一个元素。在没有初始值的空数组上调用reduce
将报错。Link to section
返回值函数累计处理的结果
例子
求数组[1,2,3,4,5]
里所有值的和
// 1 遍历求和
let count = 0;
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
count += arr[i];
}
console.log(count);
// output 15
// 2 eval
let count = eval([1, 2, 3, 4, 5].join("+"));
console.log(count);
// output 15
// 3 reduce
let count = [1, 2, 3, 4, 5].reduce((a, b) => a + b);
console.log(count);
// output 15
将二维数组转化为一维
var flattened = [
[0, 1],
[2, 3],
[4, 5],
].reduce((acc, cur) => acc.concat(cur), []);
计算数组中每个元素出现的次数
var names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
} else {
allNames[name] = 1;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
使用扩展运算符和initialValue
绑定包含在对象数组中的数组
// friends - an array of objects
// where object field "books" - list of favorite books
var friends = [
{
name: "Anna",
books: ["Bible", "Harry Potter"],
age: 21,
},
{
name: "Bob",
books: ["War and peace", "Romeo and Juliet"],
age: 26,
},
{
name: "Alice",
books: ["The Lord of the Rings", "The Shining"],
age: 18,
},
];
// allbooks - list which will contain all friends' books +
// additional list contained in initialValue
var allbooks = friends.reduce(
function (prev, curr) {
return [...prev, ...curr.books];
},
["Alphabet"]
);
// allbooks = [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// 'Romeo and Juliet', 'The Lord of the Rings',
// 'The Shining'
// ]
数组去重
let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
let result = arr.sort().reduce((init, current) => {
if (init.length === 0 || init[init.length - 1] !== current) {
init.push(current);
}
return init;
}, []);
console.log(result); //[1,2,3,4,5]
数组取最大值和最小值
let data = [1, 4, 2, 2, 4, 5, 6, 7, 8, 8, 9, 10];
//取最小值
let min = data.reduce((x, y) => (x > y ? y : x));
//取最大值
let max = data.reduce((x, y) => (x > y ? x : y));
ES5的实现
if (!Array.prototype.reduce) {
Object.defineProperty(Array.prototype, "reduce", {
value: function (callback /*, initialValue*/) {
if (this === null) {
throw new TypeError(
"Array.prototype.reduce " + "called on null or undefined"
);
}
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// >>表示是带符号的右移:按照二进制把数字右移指定数位,高位如符号位为正补零,符号位负补一,低位直接移除
// >>>表示无符号的右移:按照二进制把数字右移指定数位,高位直接补零,低位移除。
// Steps 3, 4, 5, 6, 7
var k = 0;
var value;
if (arguments.length >= 2) {
value = arguments[1];
} else {
while (k < len && !(k in o)) {
k++;
}
// 3. 长度为0 且初始值不存在 抛出异常
if (k >= len) {
throw new TypeError(
"Reduce of empty array " + "with no initial value"
);
}
value = o[k++];
}
// 8. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kPresent be ? HasProperty(O, Pk).
// c. If kPresent is true, then
// i. Let kValue be ? Get(O, Pk).
// ii. Let accumulator be ? Call(
// callbackfn, undefined,
// « accumulator, kValue, k, O »).
if (k in o) {
value = callback(value, o[k], k, o);
}
// d. Increase k by 1.
k++;
}
// 9. Return accumulator.
return value;
},
});
}
以上就是深入解析JS中数组reduce方法(附代码)的详细内容,更多请关注php爱好者其它相关文章!
-
如何注册谷歌账号(谷歌账号注册方法) 怎么跳过手机验证 时间:2025-09-29
-
access数据库8个经典实例 时间:2025-09-29
-
mmc.exe是什么进程 mmc.exe应用程序错误的原因及解决方法 时间:2025-09-29
-
4种基本的编程命名规范介绍(匈牙利命名法、驼峰式命名法、帕斯卡命名法、下划线命名法) 时间:2025-09-29
-
Ghostscript下载、安装教程 Ghostscript命令参数详解 时间:2025-09-29
-
Linux中内存管理NUMA架构详解 时间:2025-09-29
今日更新
-
揭秘网络四大梗:爆笑名场面背后的神转折,一次看懂全网热梗来龙去脉!
阅读:18
-
四大狗贼是什么梗?揭秘网络热词背后的爆笑真相,看完秒懂!
阅读:18
-
四大虐梗是什么梗?揭秘网络最扎心四大名场面,看完泪崩!
阅读:18
-
全境封锁手游需要什么配置-全境封锁手机配置
阅读:18
-
恋与制作人2025中秋节福利情报-登录可获得中秋赠礼
阅读:18
-
燕云十六声跑图长鸣玉获得方法-快速积攒长鸣玉
阅读:18
-
第五人格第四十赛季精华1时装囚徒黎明赋格设计公布
阅读:18
-
元梦之星美团皮肤怎么获取-圆梦美团皮肤获取
阅读:18
-
华夏绘世录中秋活动金秋献瑞明日开启-参与得奖励
阅读:18
-
QQ飞车T车孙悟空有什么特性-孙悟空赛车技能
阅读:18