如何在javascript中访问reducer的累加器

问题描述 投票:0回答:3

我需要获取累加器的值,我得到记录但不恢复该值。

感谢大家。

马特。

let seq = [-2, 1, -3, 4, -1, 2, 1, -5, 4];


var maxSequence = function(arr){
  let valMax = -999999999999999999;
  let result = 0;
  for(let i = 0; i < arr.length; i++){
    count(spliceArr(arr ,i, arr.length));

  }
}

function spliceArr(arr, index, arrLength){
  return arr.slice(index, arrLength)
}

function count(arr){
    return arr.reduce((accumulator, currentValue) => {    
                        console.log(accumulator);   // <= I need this value
                        return accumulator + currentValue 
                      })
}


maxSequence(seq)
javascript ecmascript-6 reduce reducers
3个回答
0
投票

您可以将累加器改为数组,仅使用计算中的最后一项。

function count(arr) {
  return arr.reduce((accumulator, currentValue) => {
    accumulator.push(+accumulator.slice(-1) + currentValue);
    return accumulator;
  }, []);
}

let seq = [-2, 1, -3, 4, -1, 2, 1, -5, 4];


var maxSequence = function(arr){
  let valMax = -999999999999999999;
  let result = 0;
  for(let i = 0; i < arr.length; i++){
    console.log('before: ', spliceArr(arr ,i, arr.length));
    console.log('after: ', count(spliceArr(arr ,i, arr.length)));
  }
}

function spliceArr(arr, index, arrLength){
  return arr.slice(index, arrLength)
}

function count(arr) {
  return arr.reduce((accumulator, currentValue) => {
    accumulator.push(+accumulator.slice(-1) + currentValue);
    return accumulator;
  }, []);
}

maxSequence(seq)

0
投票

使用现在的代码,您可以将值推送到数组并根据需要使用它们。

function count(arr){
    let accumulatorArr = [];
    return arr.reduce((accumulator, currentValue) => {    
                        // <= now you have an array of accumulator
                        accumulatorArr.push(accumulator);   
                        return accumulator + currentValue 
                      })
}


0
投票

如果你想要积累的所有结果而不是最终结果。感觉就像map操作更有意义。

let seq = [-2, 1, -3, 4, -1, 2, 1, -5, 4];


var maxSequence = function(arr){
  let valMax = -999999999999999999;
  let result = 0;
  for(let i = 0; i < arr.length; i++){
    console.log('before: ', spliceArr(arr ,i, arr.length));
    console.log('after: ', count(spliceArr(arr ,i, arr.length)));
  }
}

function spliceArr(arr, index, arrLength){
  return arr.slice(index, arrLength)
}

function count(arr){
    let accumulator = 0;
    return arr.map(currentValue => {
      accumulator += currentValue;
      return accumulator;
    })
}


maxSequence(seq)
© www.soinside.com 2019 - 2024. All rights reserved.