javascript - How to change a global variable with an ifelse statement - Stack Overflow

I have this code where i want to change var n ifthe var thisRoll is not 'green', but i only

I have this code where i want to change var n if the var thisRoll is not 'green', but i only get undefined in the output from console.log(n)

var thisRoll = 'red'
var n;
var base_bet = 1;

function betInput(thisRoll, n) {
    var x;
    if (thisRoll === 'green') {
        x = base_bet;
        n = 0;
    } else {
        n = n + 1;
    }
    return x;
}
var X = betInput(thisRoll);
console.log(X);
console.log(n);

Shouldn't it add 1 when the thisRoll aren't 'green'?

I have this code where i want to change var n if the var thisRoll is not 'green', but i only get undefined in the output from console.log(n)

var thisRoll = 'red'
var n;
var base_bet = 1;

function betInput(thisRoll, n) {
    var x;
    if (thisRoll === 'green') {
        x = base_bet;
        n = 0;
    } else {
        n = n + 1;
    }
    return x;
}
var X = betInput(thisRoll);
console.log(X);
console.log(n);

Shouldn't it add 1 when the thisRoll aren't 'green'?

Share Improve this question asked Nov 29, 2016 at 13:23 McMuffinDKMcMuffinDK 4313 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

Because your n is also a parameter in the function. So it hides the outer variable n in the function and when you access the n, it refers to the parameter variable. To work with the global n, you need to remove the parameter, or change it's name.

function betInput(thisRoll) {
    var x;
    if (thisRoll === 'green') {
        x = base_bet;
        n = 0;
    } else {
        n = n + 1;
    }
    return x;
}

The function betInput(thisRoll, n) contains a parameter n which shadows the global variable n. Calling that function using betInput(thisRoll) merely sets the local n to a default value.

(The fact that Javascript is lax on this - and many other things - does make it difficult to write stable code in the language).

Simply remove n from the function parameter list and all will be well.

Remove the parameter in your function. There's n there, which makes it scoped to the function.

function betInput(thisRoll, n) {
//------------------------^^^

Change your function to:

function betInput(thisRoll) {

So that, n will reference your global variable, otherwise n is undefined in your function scope

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744381581a4571457.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信