Javascript 在 foreach 外部添加一个元素,但它们连接而不是添加
Javascript adding an element outside the foreach but they concatenate instead of adding
我有一个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
将抛出一个 error.Use 映射 function.Hopefully 以下代码段将很有用。
另外 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)
您也可以使用 reduce
var a= [38, 34, 22, 19];
var output = a.reduce( (ac,c,i) => ( ac.push(ac.length == 0 ? c : c + ac[i-1] ) , ac ) , [] );
console.log(output);
我有一个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
将抛出一个 error.Use 映射 function.Hopefully 以下代码段将很有用。
另外 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)
您也可以使用 reduce
var a= [38, 34, 22, 19];
var output = a.reduce( (ac,c,i) => ( ac.push(ac.length == 0 ? c : c + ac[i-1] ) , ac ) , [] );
console.log(output);