之前的文章《浅谈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 evallet count = eval([1, 2, 3, 4, 5].join("+"));console.log(count);// output 15// 3 reducelet 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 booksvar 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 initialvaluevar 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; }, });}
推荐学习:javascript视频教程
以上就是深入解析js中数组reduce方法(附代码)的详细内容。