Javascript 如果第一个if语句为true,如何使代码在第一个if语句之后停止?
我正在练习一些非常基本的编码,我一直在尝试创建一个生成随机值的代码,并根据该值发布不同的消息。 问题是,当随机值满足“更多如果”的条件时,它将发布所有消息。 我尝试在每个条件后插入break,但得到的break语句无效Javascript 如果第一个if语句为true,如何使代码在第一个if语句之后停止?,javascript,Javascript,我正在练习一些非常基本的编码,我一直在尝试创建一个生成随机值的代码,并根据该值发布不同的消息。 问题是,当随机值满足“更多如果”的条件时,它将发布所有消息。 我尝试在每个条件后插入break,但得到的break语句无效 const min=1; let healthPoints=Math.floor(Math.random()*(max-min)) console.log(`You currently have ${healthPoints} HP!`) if (healthPoints&
const min=1;
let healthPoints=Math.floor(Math.random()*(max-min))
console.log(`You currently have ${healthPoints} HP!`)
if (healthPoints<90){
console.log("You're fine!")
}
if (healthPoints<50){
console.log("You're not!")
}
if (healthPoints<10){
console.log("You're f**ked")
}
这是我在控制台中得到的:
你目前有46点生命!
你很好!
你不是 如果需要不断检查语句,则需要使用else(如果不是这样的话)
const min=1;
let healthPoints=Math.floor(Math.random()*(max-min))
console.log(`You currently have ${healthPoints} HP!`)
if (healthPoints<90){
console.log("You're fine!")
}
else if (healthPoints<50){
console.log("You're not!")
}
else if (healthPoints<10){
console.log("You're f**ked")
}
因为如果你先从<90开始检查,那么当HP为1时,它将为真,那么你就永远不会使用其他语句,所以你需要先检查它是否<10你可以尝试使用if/else语句。另外,我建议你仔细看看你的病情顺序。因为我认为你必须反转它们才能得到想要的结果
const min=1;
let healthPoints=Math.floor(Math.random()*(max-min))
console.log(`You currently have ${healthPoints} HP!`)
if (healthPoints<10){
console.log("You're f**ked")
} else if (healthPoints<50){
console.log("You're not!")
} else if (healthPoints<90){
console.log("You're fine!")
}
或者,您可以将逻辑放入函数中,并在函数满足特定条件时返回该函数
function healthPointGenerator() {
const min=1;
let healthPoints=Math.floor(Math.random()*(max-min))
console.log(`You currently have ${healthPoints} HP!`)
if (healthPoints<10){
console.log("You're f**ked")
return
}
if (healthPoints<50){
console.log("You're not!")
return
}
if (healthPoints<90){
console.log("You're fine!")
return
}
}
healthPointGenerator(); //call the function here
你可以使用磨合状态。您可以在循环中使用break。您可以在将要实现的条件中使用return语句。您的预期输出是什么?healthPoints=5?您不能在if语句中使用break,但可以在switch语句中使用break。在一个条件下返回对易读性不是很好@Kyojimaru的回答将优雅地解决您的问题。
function healthPointGenerator() {
const min=1;
let healthPoints=Math.floor(Math.random()*(max-min))
console.log(`You currently have ${healthPoints} HP!`)
if (healthPoints<10){
console.log("You're f**ked")
return
}
if (healthPoints<50){
console.log("You're not!")
return
}
if (healthPoints<90){
console.log("You're fine!")
return
}
}
healthPointGenerator(); //call the function here