gpt4 book ai didi

javascript - 如何对数组中的特定元素求和?

转载 作者:行者123 更新时间:2023-12-02 02:08:48 26 4
gpt4 key购买 nike

我正在尝试操作一个数组。对于每个操作,我需要向两个给定索引之间的每个数组元素添加一个值(包含两个索引)。这是一个例子:

0 1 100  // From index 0 to 1, add 100
1 4 100 // From index 1 to 4, add 100
2 3 100 // From index 2 to 3, add 100

// Expected Result:
[100, 200, 200, 200, 100]

// Explanation:
[100, 100] // After the first update.
[100, 200, 100, 100, 100] // After the second update.
[100, 200, 200, 200, 100] // After the third update.

这是我所得到的:

function arrayManipulation(n, queries) {
let newArr = [];
for (let i = 0; i < queries.length; i++) {
let indexIni = queries[i][0];
let indexEnd = queries[i][1];
let indexSum = queries[i][2];

for (indexIni; indexIni < indexEnd; indexIni++) {
console.log(indexIni, indexEnd, indexSum);
newArr.splice(indexIni, 0, indexSum);
}
}
console.log(newArr);
}

let n1 = 5;
let queries1 = [
[0, 1, 100],
[1, 4, 100],
[2, 3, 100]
];
arrayManipulation(n1, queries1);

我试图做的是在 splice() 的第二个参数之上工作,以便我可以以某种方式将其添加到我要输入的数字。

我正在尝试的方式,可能吗?或者有更简单的方法吗?

最佳答案

1)循环应该达到

indexIni <= indexEnd

2) 从头开始​​迭代并检查该特定索引中是否存在任何数字。如果是,则添加 indexSum,否则将值设置为 indexSum

function arrayManipulation(n, queries) {
let newArr = [];
for (let i = 0; i < queries.length; i++) {
let [indexIni, indexEnd, indexSum] = queries[i];

for (indexIni; indexIni <= indexEnd; indexIni++) {
if (newArr[indexIni]) {
newArr[indexIni] += indexSum;
} else {
newArr[indexIni] = indexSum;
}
}
}
console.log(newArr);
}

let n1 = 5;
let queries1 = [
[0, 1, 100],
[1, 4, 100],
[2, 3, 100],
];
arrayManipulation(n1, queries1);

关于javascript - 如何对数组中的特定元素求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68011303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com