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

时间:2018-07-30 08:30:26

标签: javascript arrays

最终,我希望创建两个数组,将数据从一个数组移到另一个数组。

-

我一直在尝试(基于大约三个周末)基于变量的长度创建数组,但未成功;在这种情况下,我将其设置为 155 ...此步骤现已完成。

稍后我想将数组用作引用,因此选择了不对其自身进行操作。

然后,我想创建另一个数组,该数组从第一个数组获取序号以应用本质上是复利的东西。

视觉

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

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

我正在努力使这个数学动作起作用。此外,我也希望复合成分是一个变量。可以将其作为名为 variance

的变量输入到计算中
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);

1 个答案:

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