从一个数组到另一个数组的复合数

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

最终,我正在寻找创建两个数组,从一个到另一个操纵数据。

--

我一直试图(大约3个周末)尝试根据变量的长度创建一个数组;在这种情况下,我已经做到了155 ......这一步现在已经完成了。

我想稍后使用数组作为参考,因此选择不操纵自己。

然后我想创建另一个数组,从第一个数组中获取序列号,以应用基本上是复合兴趣的数组。

视觉

数组1(运行天数):1,2,3,4,5

数组2(复合数):1,3,6,10,15

我正在努力让这个数学动作起作用。此外,我也希望复合成分也是一个变量。这可以作为称为方差的变量馈入计算

let dateDifference = 155;

// creates empty array
const savingLength = [];

// iterates through length of array
for(i = 0; i < dateDifference; i++)
{
  // creates maximum days ARRAY until end of saving term
  // adds array index as array value, +1 to create iteration of days in base10
  base10 = i+1;
  savingLength.push(base10); 

}

// creates a savingAmount array that is populated with data from savingLength array
const savingAmount = savingLength.map(function(savingLength){
  // does calculation on savingAmount element and returns it

  // desired CALC. compound interest

  return savingLength + mathBit();
});


function mathBit() {
  savingAmount.forEach(saving => {

    y = saving - 1;
    x = example.startAmount;
    saving = x + y;

  });
}
console.log(savingAmount);
console.log(savingLength);
javascript arrays
1个回答
2
投票

目前,mathBit没有返回任何东西,所以当你的.map函数执行return savingLength + mathBit();时,它将无法正常工作。

使用三角数序列来计算第二个数组可能更容易:a(n) = (n * (n + 1)) / 2)

Array.from允许您从头开始创建数组而无需任何重新分配或变异。尝试这样的事情:

const dateDifference = 5;
const savingLength = Array.from(
  { length: dateDifference },
  (_, i) => i + 1
);
const savingAmount = savingLength.map(i => (i * (i + 1)) / 2);
console.log(savingLength);
console.log(savingAmount);

目前尚不清楚你对方差的确切要求,但有一种可能性就是调整三角数公式 - 将结果乘以:

const dateDifference = 5;
const savingLength = Array.from(
  { length: dateDifference },
  (_, i) => i + 1
);
const variance = 2;
const savingAmount = savingLength.map(i => variance * (i * (i + 1)) / 2);
console.log(savingLength);
console.log(savingAmount);
© www.soinside.com 2019 - 2024. All rights reserved.