people.forEach(function (dude) {
dude.pickUpSoap();});
var wallets = people.map(function (dude) {
return dude.wallet;});
var totalMoney = wallets.reduce(function (countedMoney, wallet) {
return countedMoney + wallet.money;}, 0);
var fatWallets = wallets.filter(function (wallet) {
return wallet.money > 100;});
Array.prototype.map = function (fn) {
var resultArray = [];
for (var i = 0,len = this.length; i < len ; i++) {
resultArray[i] = fn.apply(this,[this[i],i,this]);
}
return resultArray;}
Array.prototype.forEach = function (fn) {
for (var i = 0,len = this.length; i < len ; i++) {
fn.apply(this,[this[i],i,this]);
}}
Array.prototype.reduce= function (fn) {
var formerResult = this[0];
for (var i = 1,len = this.length; i < len ; i++) {
formerResult = fn.apply(this,[formerResult,this[i],i,this]);
}
return formerResult;}
JavaScript 中 map、foreach、reduce 间的区别
原文:http://www.cnblogs.com/September-9/p/5120514.html