首页 > 编程语言 > 详细

Array数组语法系列: Array.prototype.reduce

时间:2018-01-19 10:57:49      阅读:204      评论:0      收藏:0      [点我收藏+]
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;
  };
}

 看以上例子应该能明白.  

Array数组语法系列: Array.prototype.reduce

原文:https://www.cnblogs.com/laopang/p/8315363.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!