如何添加到具有函数返回值的全局变量(JavaScript)



我有一个回调函数,它接受两个参数和一个全局变量,我想用这个函数返回的值添加到其中。但是,变量保持不变。请帮忙!

let sum = 0;
const myArr = [{name: 'dj', value: '2'}, {name: 'kd', value: '3'}];
function addObjValue(arr, total) {
arr.forEach(element => {
const val = element.value;
total += checkObjValue(val);
console.log(total);
})
}
function checkObjValue(x) {
switch(x) {
case '2':
return 1;
break;
case '3':
return 5;
break;
}
}
addObjValue(myArr, sum); // sum remains 0

您可以创建一个本地变量并将总数保存在那里,然后只返回总值

function addObjValue(arr) {
let total = 0
arr.forEach(element => {
const val = element.value;
total += checkObjValue(val);
console.log(total);
})
return total
}

然后使您的总和等于返回值

sum = addObjValue(myArr);

更新还有一件事。要从数组中获取和,可以使用reduce方法

arr.reduce((totalSum, currenElement) => {
return totalSum + currenElement.value
}, 0 /*first value of totalSum (by default equal to the first element of the array)*/)

问题:

  • total的作用域在addObjValue下,因此它不会添加到最终的sum
  • 开关箱内的断路器在return 1;之后无法访问

您可以进行以下2项更改以使其正常工作。

let sum = 0;
const myArr = [{name: 'dj', value: '2'}, {name: 'kd', value: '3'}];
function addObjValue(arr, total) {
arr.forEach(element => {
const val = element.value;
total += checkObjValue(val);
})
return total; // change 1: returning total
}
function checkObjValue(x) {
switch(x) {
case '2':
return 1;
case '3':
return 5;
}
}
sum = addObjValue(myArr, sum); // change 2: assigned return value back to sum

最新更新