简体   繁体   English

调用函数而不在Javascript中输入参数

[英]Calling a function without entering its parameters in Javascript

I am trying to create a JavaScript version of an old timey dice game named PIG. 我正在尝试创建一个名为PIG的旧骰子游戏的JavaScript版本。 It involves rolling dice and keeping track of the sum of each roll. 它涉及掷骰子并跟踪每个掷骰的总和。 I need to be able to save each roll within a function and then be able to call said function to return the current roll score. 我需要能够将每个掷骰保存在一个函数中,然后能够调用所述函数以返回当前掷骰得分。


This is the method that takes the amount of the current roll and stores it into the variable total, subsequently returning the current total variable. 该方法采用当前滚动amount并将其存储到变量total中,然后返回当前total变量。

  function rollTotal(amount) {
  return amount;
  }

I first call the function and insert the score of the dice roll into the amount parameter... 我首先调用该函数,然后将骰子掷骰的分数插入到amount参数中...

var dieOne = 1;
var dieTwo = 2;
rollTotal(dieOne + dieTwo);

Then I call the function to return the current score like this... 然后我调用该函数以这样返回当前分数...

rollTotal()

and am getting this... 并得到这个...

undefined

Is there a way to set a default parameter to return the current score if a parameter is not entered when called? 如果调用时未输入参数,是否可以设置默认参数以返回当前分数?

When you call a function and don't supply a parameter, then the parameter is bound to undefined within the function. 当您调用函数而不提供参数时,该参数在函数中绑定为undefined So you can do something like this: 因此,您可以执行以下操作:

var currentAmount = undefined; // or perhaps 0?
function rollTotal(amount) {
    if (typeof(amount) === 'undefined') {
        return currentAmount;
    } else {
        currentAmount = amount;
        return amount;
    }
}

You can do this more elegantly (and more safely) using a closure: 您可以使用闭包更优雅(更安全)地执行此操作:

var rollTotal = (function() {
    var currentAmount = undefined;
    return function(amount) {
        if (typeof(amount) === 'undefined') {
            return currentAmount;
        } else {
            currentAmount = amount;
            return amount;
        }
    };
}());

You might also want to do a more robust test of the argument and treat any non-number as undefined. 您可能还想对参数进行更可靠的测试,并将所有非数字视为未定义。 You can do this with the following test: 您可以通过以下测试来做到这一点:

!isNaN(parseFloat(amount)) && isFinite(amount)

instead of testing specifically for undefined . 而不是专门针对undefined进行测试。

EDIT: As @Paul S. points out, the best test as to whether an argument was passed is arguments.length === 0 . 编辑:正如@Paul S.所指出的,关于是否传递arguments.length === 0的最佳测试是arguments.length === 0

Why use a function? 为什么要使用功能? The = operator works just fine. =运算符可以正常工作。

// initial setup
var rollTotal;

// set in the middle of an expression
"You just rolled " + (rollTotal = dieOne + dieTwo) + "!";

// recalling later in an expression
"Last time you rolled " + rollTotal + ", what will you get this time?";

A popular way to do this is with an instance of a class. 一种流行的方法是使用类的实例。

That is: 那是:

function Dice() {
    var amount;

    this.rollTotal = function(_amount) {
        // if an argument is supplied, assign it to the internal amount
        if (typeof _amount !== "number") {
            amount = _amount;
        }
        return amount;
    };
}

Example usage: 用法示例:

var dice = new Dice();
dice.rollTotal(3);
console.log(dice.rollTotal());

In JavaScript you can look at the arguments object to check whether an argument was passed or not when the function was called. 在JavaScript中,您可以查看arguments对象,以检查调用函数时是否传递了参数。 Here is how you can check if any argumemt was passed upon calling the function. 这是您如何检查调用该函数时是否传递了argumemt的方法。

function rollTotal(amount){
  if(arguments.length === 0)
     return (a value when no arguments were passed);
  else return amount;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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