美文网首页
js Array reduce

js Array reduce

作者: 钱段攻城狮 | 来源:发表于2017-11-29 15:18 被阅读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);

相关文章

网友评论

      本文标题:js Array reduce

      本文链接:https://www.haomeiwen.com/subject/wwfhvxtx.html