js Array reduce

2017-11-29  本文已影响0人  钱段攻城狮

1.数组元素叠加

function appendCurrent(previousValue, currentValue){

        return previousValue + ':' + currentValue;

}

var elements = ['abc', 'def', 123, 456];

var result = elements.reduce(appendCurrent, (initialValue));

2.[4,1,2,5] => 4125

参数:previousValue: 上一次计算的结果(第一次循环为0)

           currentDigit: 当前循环的数组元素

           currentIndex: 当前循环的数组元素索引值

           array: 对象数组

function addDigitValue(previousValue,currentDigit,currentIndex,array){

        var exponent = (array.length - 1) - currentIndex;

        var digitValue = currentDigit * Math.pow(10, exponent);

        return previousValue + digitValue;

}

var digits = [4, 1, 2, 5];

var result = digits.reduce(addDigitValue, 0);

上一篇 下一篇

猜你喜欢

热点阅读