How can I not end the while loop?

  • 0
    Hello, I'm doing a js assignment:

    Write a program that sequentially asks the user for a number using a prompt until he clicks Cancel. After clicking “Cancel”, the program displays the sum of the entered numbers using alert. If the user entered not a number (but, for example, a string), then this value is not added to the rest.


    Wrote code like this:
    let sum = 0;
     
    while (i = +prompt('Введите число: ')) {
        sum += i;
    };
    
    alert('Сумма: ' + sum);


    Everything seems to be fine, but how to make sure that the loop does not cancel when the user enters a line? You just need to skip it and when you need to display the sum of all numbers without the entered lines.
    JavaScript Anonymous, Jan 29, 2020

  • 4 Answers
  • 0
    let sum = 0;
    let strNumber = 0;
    let number = 0;
    while (strNumber !== null) {
    strNumber = prompt("Введите число:", ""); // Получаем из prompt строку либо число в виде строки, если нажата отмена то вернёт null
    number = Number(strNumber); // Приводим строку к числу, если строка не может быть числом то вернёт NaN см. https://learn.javascript.ru/type-conversions
    sum += (!isNaN(number)) ? number : 0; // Использую isNaN потому что Number.isNaN не будет работать в IE у isNaN есть особености см (https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/isNaN)
    }
    if(sum) {
    alert(sum);
    }
    Anonymous

  • 0
    Answer to the question:

    let sum = 0;

    while (i = prompt('Введите число: ')) {
    let j = parseInt(i, 10);
    if (Number.isNaN(j)) {
    continue;
    }
    sum += j;
    };

    alert('Сумма: ' + sum);




    In more detail, then your script crashed when the + prompt was applied if the user entered a letter.
    Anonymous

  • 0
    The prompt always contains a string. This string can be interpreted as a number, and in different ways, incl. as Roman notation: I, II, III, IV, V, VI, VII, VIII, IX, X, ...



    I don’t remember offhand what the prompt returns when I click Cancel. Read the documentation.

    But you certainly don't need to convert the return value to a number right away. First you need to check for cancellation, and if so, then leave the cycle.
    Anonymous

  • 0
    const arr = [];

    function setintPromt() {
    let num = prompt('Введите число: ', '');
    if (num === null) {
    let result = arr.length ? eval(arr.join('+')) : 0;
    return alert(result);
    }
    if (+num) {
    arr.push(num);
    }
    setintPromt();
    }
    setintPromt();
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!