我不知道我是否在监督它或什么,但我不知道如何获得 else if 语句的结果,例如,我有这段代码,我一直在练习:
在这种情况下,结果将是“它很温暖!”,我想做的是创建一个取决于结果的代码,但结果它不是一个变量,那么我如何创建一个代码响应记录的内容?例如,如果它记录:“天气很暖和!”我想添加诸如“打开空调”之类的内容。或“打开加热器”或其他。我该怎么做?
let temperature = 36
if (temperature > 24) {
console.log ("It's warm!");
} else if (temperature < 24) {
console.log ("It's cold!");
} else {
console.log ("It's cool!");
答案 0 :(得分:0)
您可以将其保存为变量:
let temperature = 36;
const isCold = temperature < 24;
const isWarm = temperature > 24;
if (isWarm) {
console.log("It's warm!");
} else if (isCold) {
console.log("It's cold!");
} else {
console.log("It's cool!");
}
if (isWarm) {
console.log("Turn on the A/C!");
}
答案 1 :(得分:0)
您可以在 if 条件后用 {}
定义的表达式块中设置代码..
例如:
let temperature = 36;
if (temperature > 24) {
console.log("It's warm!");
console.log("Turn on the AC.");
// You can write coode base in this condition as much you want
// or you can call another function
} else if (temperature < 24) {
console.log("It's cold!");
} else {
console.log("It's cool!");
}
答案 2 :(得分:0)
不太清楚你的意思,但如果你想输出温度:
let temperature = 36
if (temperature > 24) {
console.log ("It's warm!", temperature, "degrees");
} else if (temperature < 24) {
console.log ("It's cold!", temperature, "degrees");
} else {
console.log ("It's cool!", temperature, "degrees);
答案 3 :(得分:0)
将结果放入变量中。
let temperature = 36;
let result = '';
if (temperature > 24) {
result = "It's warm!";
} else if (temperature < 24) {
result = "It's cold!";
} else {
result = "It's cool!";
}
console.log (result);
答案 4 :(得分:0)
您可以在函数中设置一个变量 - 将温度传递给函数并输出结果 - 请注意 switch statement
的使用,它将输入的温度与条件进行比较并更新结果字符串。这就是 switch 语句的用途 - 提供嵌套或复杂 if else 语句的替代方案。
function setTemperature(temp){
let result = "It's ";
switch (true) {
case temp > 24:
result += "warm!";
break;
case temp > 12:
result += "cool!";
break;
default:
result += "cold!";
}
return result;
}
console.log( setTemperature(36)); // gives "It's warm!"
console.log( setTemperature(16)); // It's cool!
console.log( setTemperature(6)); //It's cold!
答案 5 :(得分:0)
你可以像这样创建一个函数:
let temperature = 36;
function myFunct(temp){ // "myFunct" can be anything
if (temp > 24) {
return "It's warm!";
} else if (temp < 24) {
return "It's cold!";
} else {
return "It's cool!";
}
}
var t = myFunct(temperature); // get whether it's warm, cold, or cool
console.log(t); // tell the user if it's warm, cold, or cool
// do something!
if(t === "It's warm!"){
// run something here if it's warm
} else if (t === "It's cold!"){
// run something here if it's cold
} else {
// run something here if it's cool
}
虽然你可以在函数或原始 if 语句中运行一些东西。
希望这有帮助!