JavaScript: Calling Array.reduce when outer function is called, and outer function has arguments
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 | var foo = 0; var bar = 0; var arr1 = [1, 2, 3, 4, 5]; var arr2 = [6, 7, 8, 9, 10]; function getSum(arr, sum) { sum = arr.reduce(function(accum, val) { return accum += val; }, 0) } getSum(arr1, foo); //expect foo to equal 15, but it stays at 0 getSum(arr2, bar); //expect bar to equal 40, but it stays at 0 |
我想多次使用这个函数,因此参数。我知道让
基本上,我希望
如果我正确理解你,你只需要一个这样的和函数:
1 2 3 4 5 6 7 8 9 10 11 12 | var foo = 0; var bar = 0; var arr1 = [1, 2, 3, 4, 5]; var arr2 = [6, 7, 8, 9, 10]; const getSum = (arr) => arr.reduce((r,c) => r+c) foo = getSum(arr1) bar = getSum(arr2) console.log(foo) console.log(bar) |
在JavaScript中,基元类型是按值传递的。对象通过引用传递。您可以通过将
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var foo = { value: 0 }; var bar = { value: 0 }; var arr1 = [1, 2, 3, 4, 5]; var arr2 = [6, 7, 8, 9, 10]; function getSum(arr, sum) { sum.value = arr.reduce(function(accum, val) { return accum += val; }, 0) } getSum(arr1, foo); getSum(arr2, bar); console.log(foo.value); console.log(bar.value); |
如果可能的话,你应该试着找到一种方法来解决你的问题而不致突变。
事实上,如果许多linting工具(如eslint)看到函数参数发生变化,就会抛出一个错误。
相反,您应该将
1 2 3 4 5 6 7 8 9 10 11 12 | var arr1 = [1, 2, 3, 4, 5]; var arr2 = [6, 7, 8, 9, 10]; function sum(arr) { return arr.reduce(function(acc, next) { return acc + next }); } var foo = sum(arr1); var bar = sum(arr2); console.log(foo); console.log(bar); |