如何在JavaScript中访问减速机的累加器

时间:2019-03-19 18:07:02

标签: javascript ecmascript-6 reduce reducers

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

谢谢大家。

马特。

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)

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分: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)

答案 2 :(得分: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)