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

Posted laopang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Array数组语法系列: Array.prototype.reduce相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

将类数组转化成数组

arguments

Array数组语法系列: Array.from()

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

Array.prototype.map() 之后的下一个函数是不是可以安全地假设 map 中的所有回调都已返回?

插入排序(JS代码)