如何将一个数组的值连续添加到另一个数组并将值存储在javascript中的新数组中?

How to consecutively add values from one array to another and store the value in a new array in javascript?

我有 2 个数组:

const initialAmount = [50]

const transactionAmounts = [ -10, 10, 10, -1, -5, -10, 5, 5, 5, 10, 10, 10, 1, -1, -2, -5, -10 ]

我如何 return 一个将 transactionAmounts 中的每个值添加到 initialAmount 的数组? (不包括第一个,应该是初始值)

例如应该return:

const valueAfterEachTransaction = [50, 40, 50, 60, 59, 54, 44, 49, 54, 59, 69, 79, 89, 90, 89, 87, 82, 72]

const initialAmount = [50]

const transactionAmounts = [ -10, 10, 10, -1, -5, -10, 5, 5, 5, 10, 10, 10, 1, -1, -2, -5, -10 ]

const newArray = [initialAmount[0]]
let value = initialAmount[0]
let i = 0 

do {
    value = value + transactionAmounts[i]
  newArray[i+1] = value
  i++;
}
while (i < transactionAmounts.length);
 console.log(newArray)

const initialAmount = [50]

const transactionAmounts = [ -10, 10, 10, -1, -5, -10, 5, 5, 5, 10, 10, 10, 1, -1, -2, -5, -10 ]

const newArray = [initialAmount[0]]
let value = initialAmount[0]
let i = 0 

do {
    value = value + transactionAmounts[i]
  newArray[i+1] = value
  i++;
}
while (i < transactionAmounts.length);
 console.log(newArray)

您可以对总和进行闭包并获取两个数组的所有元素以映射实际总和。

const
    initial = [50],
    transactions = [-10, 10, 10, -1, -5, -10, 5, 5, 5, 10, 10, 10, 1, -1, -2, -5, -10],
    result = [...initial, ...transactions].map((s => v => s += v)(0));

console.log(...result);

也许我在这里遗漏了一些东西,但这似乎很简单map,在你处理完丢失的初始值之后。

const combine = ([x], ys) => [0, ...ys] .map (y => x + y)

const initialAmount = [50]
const transactionAmounts = [-10, 10, 10, -1, -5, -10, 5, 5, 5, 10, 10, 10, 1, -1, -2, -5, -10] 

console .log (combine (initialAmount, transactionAmounts))
.as-console-wrapper {max-height: 100% !important; top: 0}

我很好奇您的潜在需求是什么。这似乎是一个奇怪的要求。为什么初始值在数组中传递?为什么有一个隐含的 0 添加到第一个。这是 XY problem 吗?