@fhetushr
Начинающий программист самоучка

Почему в конце выводит undefined?

"use strict"

function sumInput() {
	let number = [];
	let userInput;

	while (userInput != "exit") {
		userInput = prompt("Введите число: ", "0");
		number.push( Number(userInput) );
	}

	number.pop();
	console.log(number);

	let sum = 0;

	for (let i = 0; i < number.length; i++) {
		sum = sum + number[i];
	}

	alert(sum);
}

alert( sumInput() );


Проблемы как таковой нет, лишь только почему в конце всего это выводиться undefined =)

P.S. код работает как надо...
  • Вопрос задан
  • 212 просмотров
Решения вопроса 1
Ternick
@Ternick
Функция sumInput ничего не возвращает поэтому и undefined.
По сути тут 2 развития событий.
1)
"use strict"

function sumInput() {
  let number = [];
  let userInput;

  while (userInput != "exit") {
    userInput = prompt("Введите число: ", "0");
    number.push( Number(userInput) );
  }

  number.pop();
  console.log(number);

  let sum = 0;

  for (let i = 0; i < number.length; i++) {
    sum = sum + number[i];
  }

  alert(sum);
}

sumInput();

2)
"use strict"

function sumInput() {
  let number = [];
  let userInput;

  while (userInput != "exit") {
    userInput = prompt("Введите число: ", "0");
    number.push( Number(userInput) );
  }

  number.pop();
  console.log(number);

  let sum = 0;

  for (let i = 0; i < number.length; i++) {
    sum = sum + number[i];
  }

  return sum;
}

alert( sumInput() );

Выбирайте какой больше нравится, мне 2 вариант.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы