这个 JavaScript 代码(函数)有什么问题?

What's wrong with this JavaScript code (functions)?

抱歉,我的问题有点难,但实际上我有 2 个问题几乎是同一类型的...

第一个问题: 为什么我在这段代码中的最后三个函数不起作用...

<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <script type="text/javascript">
        //Skriver ut en strengen "Bananer og epler er ikke det samme!"
        document.write("Bananas and apples are not the same! ");
        //Variabelnavnet kan kun inneholde bokstaver, tall, og understrek. Variabelnavnet kan ikke begynne med et tall.
        var banana1 = "rotten"; 
        var banana2 = "good";
        document.write("One banana was " + banana1 + " and the other was " + banana2 + ", and they both know the song \"I'm yellow and I hate it\" very well.<br />");
        //En pop-up melding i samarbeid med XHTML.
        function bananas() 
        {alert ("Wow, what a loser u are!");}
        function cherries() 
        {alert ("That's better!");}
        //Flere parametere.
        function pineapples(one, two){
        document.write(one + " are as sweet as " + two + "<br />");
        }
        pineapples("Pineapples", "kiwis");
        pineapples("Watermelons", "citrons");
        pineapples("Dades", "apricots");
        }
        function waterMelons(){
        document.write("I loooove watermelons!");
        }            
        function ciTrons(){
        document.write("But citrons...!");
        }
        function start(){
        waterMelons();
        ciTrons();
        }
        start();
    </script>
    <form>
        <input type="button" value="Click me if u like bananas" onclick="bananas()"/>
        <input type="button" value="Click me if u like cherries" onclick="cherries()"/>
    </form>     
</body>
</html>

但是当我将最后三个函数放在一个单独的文件中时,就像这样...

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
    function waterMelons(){
        document.write("I loooove watermelons!");
        }            
        function ciTrons(){
        document.write(" But citrons...!");
        }
        function start(){
        waterMelons();
        ciTrons();
        }
        start();
</script>       
</body>
</html>

有效!为什么!?

第二题

这个代码有问题还是我像烂水果一样笨?为什么它 return 不是值“20”?

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
    <script type="text/javascript">
        function addNumbers(a,b,c){
        var d = a+b+c;
        return d;
        }
        ducument.write(addNumbers(2,6,12));
    </script>
    </body>
</html> 

两个问题都是 typos,在第一种情况下你使用了额外的 }:

    function pineapples(one, two){
      document.write(one + " are as sweet as " + two + "<br />");
    }
      pineapples("Pineapples", "kiwis");
      pineapples("Watermelons", "citrons");
      pineapples("Dades", "apricots");
    } <-- THIS IS WRONG

在第二种情况下,您使用的是 ducument 而不是 document:

ducument.write(addNumbers(2,6,12)); <-- MUST BE document

希望这对您有所帮助,