不确定我的代码是否正常运行,但是我看到的错误是“已声明“结果”,但其值从未读取。ts(6133)”
这只是一个介绍性练习,因此我对如何完成同一件事持开放式建议/指导。我这样做的方式是针对事件类型使用三个IF语句,并在每个温度范围内嵌套IF语句。
let eventType = window.prompt("What type of event are you going to?");
let tempFahr = window.prompt("What is will the temperature be?");
if (eventType=='casual') { // casual event
if (tempFahr < 54) { // temp less than 54
let result = 'Since it is ' + tempFahr + ' and you are going to a ' + eventType + ' event, you should wear something comfy and a coat';
} else if (54 < tempFahr < 70) { // temp between 54 and 70
let result = 'Since it is ' + tempFahr + ' and you are going to a ' + eventType + ' event, you should wear something comfy and a jacket';
} else { // temp more than 70
let result = 'Since it is ' + tempFahr + ' and you are going to a ' + eventType + ' event, you should wear something comfy and no jacket';
}
} else if (eventType=='semi-formal') { // semi-formal event
if (tempFahr .. (Etc.)...
``````````````
{
let result = 'Since it is ' + tempFahr + ' and you are going to a ' + eventType + ' event, you should wear a suit and no jacket';
}
}
console.log(result);
答案 0 :(得分:4)
let
是块作用域的-您需要在result
语句之外声明if
:
let eventType = window.prompt("What type of event are you going to?");
let tempFahr = window.prompt("What is will the temperature be?");
let result = "";
if (eventType == "casual"){
if (tempFahr < 54){
result = 'Since it is ' + tempFahr + ' and you are going to a ' + eventType + ' event, you should wear something comfy and a coat';
}
//...
}
else if (eventType == "semi-formal") {...}
console.log(result);
块作用域确定意味着用let
或const
在代码{}
的“块”中声明不会在该块外部存在,而仅在其内部。因此,let result = "..."
语句内的if
意味着result
将被删除,而其他所有将完全不同。它们将被垃圾回收,因为在if
语句之外没有对它们的引用。