我有一个foreach
var a= [38, 34, 22, 19];
Array.forEach(function (b){
b= a+ b;
a.push(b);
});
但是当结果是
["38", "3834", "38,383422", "38,3834,38,38342219"]
我怎样才能阻止它们连接并得到结果
["38, "72", "94", "119"]
最佳答案
Array.forEach
将抛出错误。使用映射函数。希望以下代码片段有用。
此外a.push(b);
将插入同一个数组
var a = [38, 34, 22, 19];
// create a variable to store the updated value
var tempNum = 0;
//use map which will return a new array
var m = a.map(function(b) {
//update tempValue with new value
tempNum = tempNum + b
return tempNum; // return tempNum
});
console.log(m)
关于Javascript 在 foreach 之外添加一个元素,但它们是连接而不是添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48335864/