尝试将数组的两个元素相加,即[2,4,6,8,10,12] 应该返回一个新数组 [6, 14, 22] (2+4, 6+8, 10+12)[4,2,7,15,35,23] 应该返回一个新数组 [6,22,58] - (4+2, 7+15, 35+23)新的、沮丧的并且无法正确地制定一个 for 循环来达到预期的结果。到目前为止我尝试过的错误解决方案: var newArray = []; for (let i = 0; i<numbers.length - 1; i +=2) { newArray = numbers.push(numbers[i] + numbers[i] + 1); console.log(newArray); }
2 回答
翻阅古今
TA贡献1780条经验 获得超5个赞
你很接近:
let newArray = [];
const numbers = [2,4,6,8,10,12];
for (let i = 0; i < numbers.length - 1; i += 2) {
newArray.push(numbers[i] + numbers[i + 1]);
}
console.log(newArray);
SMILET
TA贡献1796条经验 获得超4个赞
快速简单,假设输入总是一个偶数长度的数组
const data = [4,2,7,15,35,23]
const length = data.length
const res = []
for(let i = 0; i < length; i+=2){
var num1 = data[i]
var num2 = data[i + 1]
res.push(num1 + num2)
}
console.log(res)
添加回答
举报
0/150
提交
取消