编码的Javascript无效

时间:2016-08-06 02:58:58

标签: javascript html

编码到我的html中的javascript无效。它应该找到列出的球员中最好的,然后警告谁是最好的。当我运行它时,所有HTML和CSS方面都显示,但没有警报。请帮忙。它可能只是语法错误或其他什么,但请继续帮助!这是代码:

<script>
            var players = [
                {name: "Pat Moran", overall: 67, position: 1},
                {name: "Peter Webb", overall: 81, position: 1},
                {name: "Ramiro Ramirez", overall: 74, position: 1}
            ];

            function findBestPlayer() {
                var bestSoFar = 0;
                var bestPlayer;
                for (var i = 0; i < players.length; i++) {
                    if (players[i].overall > bestSoFar) {
                        bestPlayer = players[i];
                        bestSoFar = players[i].overall;
                    }
                }
                return best;
            }

            var bestPlayer = findBestPlayer();
            alert("Best player is " + bestPlayer.name + " with an overall of " + bestPlayer.overall ;
        </script>

4 个答案:

答案 0 :(得分:1)

return best;未定义 - 在该位置使用return bestPlayer;,并在警报结束后包含大括号

答案 1 :(得分:1)

            var players = [
                {name: "Pat Moran", overall: 67, position: 1},
                {name: "Peter Webb", overall: 81, position: 1},
                {name: "Ramiro Ramirez", overall: 74, position: 1}
            ];

            function findBestPlayer() {
                var bestSoFar = 0;
                var bestPlayer;
                for (var i = 0; i < players.length; i++) {
                    if (players[i].overall > bestSoFar) {
                        bestPlayer = players[i];
                        bestSoFar = players[i].overall;
                    }
                }

                return bestPlayer;
            }

            var bestPlayer = findBestPlayer();
            alert("Best player is " + bestPlayer.name + " with an overall of " + bestPlayer.overall) ;
警报功能缺少右括号。 编辑:更正了bestPlayer而不是最佳。感谢跑步者和约瑟夫。

答案 2 :(得分:1)

我正在回答这个问题,所以我无法调试它,但是在函数findBestPlayer中你返回的最好而不是bestPlayer。

答案 3 :(得分:1)

此处最好没有定义并且在警告中缺少括号

 var players = [
                {name: "Pat Moran", overall: 67, position: 1},
                {name: "Peter Webb", overall: 81, position: 1},
                {name: "Ramiro Ramirez", overall: 74, position: 1}
            ];

            function findBestPlayer() {
                var bestSoFar = 0;
                var bestPlayer;
                for (var i = 0; i < players.length; i++) {
                    if (players[i].overall > bestSoFar) {
                        bestPlayer = players[i];
                        bestSoFar = players[i].overall;
                    }
                }
                return bestPlayer;
            }
          var bestPlayer = findBestPlayer();
            alert("Best player is " + bestPlayer.name + " with an overall of " + bestPlayer.overall) ;