簡體   English   中英

是否需要在Javascript函數中定義參數?

[英]Is it required to define parameters in a Javascript function?

是否需要在javascript函數中定義參數? 我的問題是關於我下面的comchoice函數,我只是使用open和close括號而不提供任何可以更改的參數。

我列出了腳本的完整代碼,僅供參考

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
var compchoice = function ()
{
    if (computerChoice <= 0.34) 
    {
        return computerChoice = "Rock";
    } 
    else if(0.35 <= computerChoice <= 0.67) 
    {
        return computerChoice = "Paper";
    } 
    if (0.68 <= computerChoice <= 1)
    {
        return computerChoice = "Scissors";
    }
};

compchoice();

var compare = function (choice1, choice2)
{
    if (choice1 === choice2)
    {
        return alert("The result is a tie!");
    }

    if (choice1 === "Rock")
    {
        if (choice2 === "Scissors")
        {
            return alert("Rock wins!");
        }
        else if (choice2 === "Paper")
        {
            return alert("Paper wins!");
        }
    }
    else if (choice1 === "Scissors")
    {
        if (choice2 === "Rock")
        {
            return alert("Rock wins!");
        }
        else if (choice2 === "Paper")
        {
            return alert("Schissors wins!");
        }
    }
};

compare(userChoice, computerChoice);

不,沒有必要傳遞參數,功能可以沒有參數。 在你的情況下,函數正在使用閉包訪問外部變量。

你可以做的是如下:

function RandomFunction(){
   alert( arguments[0] );
   console.log( arguments[1] );
}

RandomFunction( 'Hello World', 'Good bye' );

並在函數中的“arguments”變量中查找函數的參數。 因此,不需要聲明參數,但聲明它們總是一個很好的方法。

此外,您可以傳入一個對象作為可擴展的對象列表,而不是使用傳統參數:

function AnotherFunction( x ){
   alert( x.message );
}

AnotherFunction( {message: 'Hello Again, world'} );

根據函數定義語法

FunctionExpression:
function Identifier opt (FormalParameterList opt ){FunctionBody} ES5§13

在函數表達式中,您可以省略標識符和參數。

因此,您的代碼在語法上是有效的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM