Search code examples
javascriptprompt

show prompt while the user cancels, it gets uncaught typeError


I have declared a function called init(), it ask the users the game size, which is separated by the space. I want to show the prompt while the user doesn't click on ok and acts like cancel (explicitly click on the cancel or implicitly press the esc keyboard).

Here is what I have implemented:

function init(){
    let promptMessage = 'تعداد سطرها و ستون‌های جدول را به ترتیب وارد کرده و با فاصله از هم جدا کنید\nمثلا مقدار پیش‌فرض دارای 7 جدول و 6 ستون است';
    let promptDefault = '7 6';
    let prompt = this.prompt(promptMessage, promptDefault);
    if (prompt) {
        prompt = prompt.split(" ")
        console.log(prompt);
        prompt[0] = Number(prompt[0]);
        prompt[1] = Number(prompt[1]);
        return prompt;
    }
    init()
}

var gameSize = init(),
    rows = gameSize[0],
    cols = gameSize[1];

When I test the above code, after I click on the cancel, it works correctly and show the prompt again but the problem is that it gives me the following error.

Uncaught TypeError: Cannot read property '0' of undefined in line rows = gameSize[0]


Solution

  • When you call gameSize = init() it runs the init() function and if the user hits cancel the function will return undefined because you do not declare a return statement in that code path.

    Then when you do var rows = gameSize[0], gameSize is undefined at that point and results in the error you see.

    What you need to do is return the result from the next call of init().

    function init(){
        let promptMessage = 'تعداد سطرها و ستون‌های جدول را به ترتیب وارد کرده و با فاصله از هم جدا کنید\nمثلا مقدار پیش‌فرض دارای 7 جدول و 6 ستون است';
        let promptDefault = '7 6';
        let prompt = this.prompt(promptMessage, promptDefault);
        if (prompt) {
            prompt = prompt.split(" ")
            console.log(prompt);
            prompt[0] = Number(prompt[0]);
            prompt[1] = Number(prompt[1]);
            return prompt;
        }
        return init();
    }
    
    var gameSize = init(),
        rows = gameSize[0],
        cols = gameSize[1];