简体   繁体   中英

Is it required to define parameters in a Javascript function?

Is it required to define parameters in a javascript function? My question is regarding my comchoice function down below, where I simply use the open and close parentheses without giving any parameters that can be changed.

I listed my full code for the script just for reference

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);

No, it is not necessary to pass parameter, function can be with no parameter. In your case function is accessing the outer variables with closures.

What you can do is something like the following:

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

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

And find the arguments for the function in the "arguments" variable within a function. Thus, no need to declare the argument, but declaring them is always a great way to go.

Also, instead of using traditional arguments, you can pass in an object to be used as an extensible list of objects:

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

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

As per the Function Definition Syntax

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

In a function expression you can ommit the identifier as well as the parameters.

Hence your code is syntactically valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM