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

时间:2017-08-11 15:44:46

标签: javascript arrow-functions

我在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>

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

0 个答案:

没有答案