我对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>结果值是字符串而不是数字。对于括号,我尝试了不同的插入选项,但它对我不起作用。我在哪里搞错了?
发布于 2017-08-11 15:49:56
您不需要这个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>
发布于 2017-08-11 16:01:49
这将使用自动执行的匿名箭头函数来实现您想要的结果:
<!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>正如其他人指出的那样,在这种特殊情况下,额外的功能是不必要的。但是,它显示了如何处理需要嵌套函数的类似问题,例如,如果您在循环中定义函数。
https://stackoverflow.com/questions/45639080
复制相似问题