[英]Assign to variable with arrow function doesn't work properly
我在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>
结果值是字符串而不是数字。 我为括号尝试了不同的插入选项,但是它对我不起作用。 我在哪里做错了?
您不需要此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>
这使用自执行的匿名箭头功能来实现所需的功能:
<!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>
正如其他人指出的那样,在这种特定情况下,不需要额外的功能。 但是,它显示了在需要嵌套函数的情况下如何解决类似的问题,例如,如果要在循环中定义函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.