var books = [ { title: "Showings", author: "Julian of Norwich", checkouts: 45 }, { title: "The Triads", author: "Gregory Palamas", checkouts: 32 }, { title: "The Praktikos", author: "Evagrius Ponticus", checkouts: 29 } ]; function doSum(arr) { var total = 0; if(!arr) return total; for(var i = 0, ilen = arr.length; i < ilen; i ++) { var arri = arr[i]; total += arri.checkouts; } return total; } //Ouputs: 106 console.log(doSum(books)); function doSum(arr) { return arr.map(function(item) { return item.checkouts; }) .reduce(function(prev, cur) { return prev + cur; }); } var relArray = [ ["Viola", "Orsino"], ["Orsino", "Olivia"], ["Olivia", "Cesario"] ]; var relMap = relArray.reduce(function(memo, curr) { memo[curr[0]] = curr[1]; return memo; }, {}); //注意此处有个初始值 /*Outputs: { "Viola": "Orsino", "Orsino": "Olivia", "Olivia": "Cesario" }*/ console.log(relMap); Array.prototype.reduce = Array.prototype.reduce || function(callback, opt_initialValue){ ‘use strict‘; if (null === this || ‘undefined‘ === typeof this) { // At the moment all modern browsers, that support strict mode, have // native implementation of Array.prototype.reduce. For instance, IE8 // does not support strict mode, so this check is actually useless. throw new TypeError( ‘Array.prototype.reduce called on null or undefined‘); } if (‘function‘ !== typeof callback) { throw new TypeError(callback + ‘ is not a function‘); } var index, value, length = this.length >>> 0, isValueSet = false; if (1 < arguments.length) { value = opt_initialValue; isValueSet = true; } for (index = 0; length > index; ++index) { if (this.hasOwnProperty(index)) { if (isValueSet) { value = callback(value, this[index], index, this); } else { value = this[index]; isValueSet = true; } } } if (!isValueSet) { throw new TypeError(‘Reduce of empty array with no initial value‘); } return value; }; }
看以上例子应该能明白.