我在尝试此提示程序时遇到了引用/ NaN错误

时间:2018-01-23 01:48:45

标签: javascript

我正在使用TheOdinProject的一个非常简单的javascript程序,我的代码会一直返回错误,特别是:

ReferenceError:未定义响应     在评论:13:9     在eval     在新的承诺

let number = prompt('what is your favorite number?');

if (number == 42) {
  let response = ("Yay! That's my favorite too!');
}
else if (number < 42) {
  let response = 'Eh, that's OK but x would be even better.';
}
else {
  let response = 'LAME. That number is too large!';
}

let x = ++response;

console.log(response)

我无法想象我做错了什么。起初,我得到了NaN错误,所以我用引号(&#34; 42&#34;)将42作为一个字符串,但这也没有用。我也尝试将第一行更改为:let number = Number(提示(&#39;你最喜欢的号码是什么?&#39;));认为这个号码可能没有转换为数字。

如果我需要提供更多信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

let是块范围的,因此response变量仅存在于每个if / else if / else块中。您可以尝试在这些块之外声明它:

let number = prompt('what is your favorite number?');
let response; // Declare here.

if (number == 42) {
  // Take care not to redeclare it here. Notice the lack of `let`.
  response = "Yay! That's my favorite too!";
}
else if (number < 42) {
  response = "Eh, that's OK but x would be even better.";
}
else {
  response = 'LAME. That number is too large!';
}

let x = ++response;

console.log(response)

我也注意到你的一些引用不匹配。不确定你的原始代码是否那样,但如果字符串本身包含单引号,请确保避免使用单引号(以避免提前终止字符串)。

另外,您还应该知道++response无法正常工作,因为response是字符串,而不是数字。