Array changing of order

Asked

Viewed 65 times

1

I’m new to javascript and I’m making a little game to learn the language. The idea is simply to ask the user to tell the sequence of the pi number and, in case of error, stop the program and give a score to the user. I am running the program on Node.

This is my code:

let rl = require('readline')


//funcao para copiar método format do python
String.prototype.format = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

let prompt = rl.createInterface(process.stdin, process.stdout)

// Array contendo a sequencia do número pi
let array_pi = String(Math.PI).replace('.','').split("")

prompt.question('Please, type the pi value:', function(exp){
    let i = 0
    while (array_pi[i]==exp){
        prompt.question('Next:', exp)
        i++
    }
    console.log('Wrong answer!.Your score was {0}'.format(i))
    process.exit()
})

The problem is that the condition within the while is always giving false even when I give the true number. It looks like JS is rearranging the array. Is that normal? How do I get him to keep the array in the order I put it?

  • reply to deleted comment:What I thought was the user playing one number at a time. If you play 3, the program asks for the next one, if you play 1, ask for the next one, and so on. Suppose the user plays 7 on the third, then gives error and the program ends. Then the comparison would be array_pi[i]==exp even

1 answer

2


The problem is caused by the fact that the function . Question() is asynchronous. That is, what is after it runs regardless of what is inside (which runs after the user enters). This is solved by recursively calling the function (i.e., the function calls itself).

This is a classic mistake in Javascript.

Code working:

let rl = require('readline')


//funcao para copiar método format do python
String.prototype.format = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

let prompt = rl.createInterface(process.stdin, process.stdout)

// Array contendo a sequencia do número pi
let array_pi = String(Math.PI).replace('.','').split("")


let funcao = function(indicePi) {
    prompt.question('Entre o digito de PI para o algorismo ' + (indicePi+1) + ': ', function(exp){

        if((array_pi[indicePi] != exp)) {
            console.log('Wrong answer!.Your score was {0}'.format(indicePi))
            process.exit()
        }
        else {
            indicePi++;

            // chamar recursivamente a função
            funcao(indicePi);
        }
    })  
}

let indicePi = 0;
funcao(indicePi);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.