最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论