使用箭头功能分配给变量无法正常工作



我在javascript中使用箭头函数有问题。当我尝试时

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the sum of the numbers in the array.</p>
<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<script>
var numbers = [1, 2, 3, 4];
function myFunction() {
const result =
numbers.reduce(
(total, sum) => total + sum
);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>

它工作正常。但是当我尝试时

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the sum of the numbers in the array.</p>
<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<script>
var numbers = [1, 2, 3, 4];
function myFunction() {
const result = numbers =>
numbers.reduce(
(total, sum) => total + sum
);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>

结果值是字符串而不是数字。我尝试了括号的不同插入选项,但它对我不起作用。我哪里做错了?

这使用自执行的匿名箭头函数来实现您想要的:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the sum of the numbers in the array.</p>
<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<script>
var numbers = [1, 2, 3, 4];
function myFunction() {
const result = (numbers => numbers.reduce(
(total, sum) => total + sum
))(numbers);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>

正如其他人指出的那样,在这种特定情况下不需要额外的功能。但是,它显示了如何处理需要嵌套函数的类似问题,例如,如果您在循环中定义函数。

你不需要这个const result = numbers => numbers.reduce...,或者更具体地说你不需要numbers =>,你可以让它变得如此const result = numbers.reduce(...

类似于不使用箭头功能的情况。

编辑

我已经更新了代码片段以包含可以接受参数的函数。

通过使用:

var myFunction = (numberArr) =>{//code here}

然后,您可以将numbers传递到您选择的myFunction()或其他数组中。因此,html 已更新以反映这一点:

<button onclick="myFunction(numbers)">Try it</button>

<html>
<body>
<p>Click the button to get the sum of the numbers in the array.</p>
<button onclick="myFunction(numbers)">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<script>
var numbers = [1, 2, 3, 4];
var myFunction = (numberArr) => {
const result = numberArr.reduce(
(total, sum) => total + sum
);
document.getElementById("demo").innerHTML = result;
console.log(typeof result)
}


</script>
</body>
</html>

最新更新