input = window.prompt()
x = true
if (input.includes("stop working")) {
if (x = true) {
console.log("not working")
}
x = false
}
if (x = true) {
console.log("working")
}
理论上,当我在窗口提示中输入stop working
时,它不应记录working
,但是当我输入stop working
时,即使not working
为working
,它也会记录x
,然后记录false
。并且只有在为working
时才应记录为真。
问题出在这里if(x=true)
,您正在将默认参数传递给x
,所以它总是正确的,在这种情况下,正确的是:
input = window.prompt()
x = true
if(input.includes("stop working")){
if(x == true){
console.log("not working")
}
x=false
}
if(x){ // here
console.log("working")
}
如果要使用比较变量,则必须使用==
或===
,如下所示:
input = window.prompt()
x = true
if(input.includes("stop working")){
if(x == true){
console.log("not working")
}
x=false
}
if(x == true){ // here
console.log("working")
}
但是,在这种情况下,您的变量是一个布尔值,因此不需要在if
中进行此比较。
并且如果您想要更多的优化代码,则可以执行此操作:
input = window.prompt()
if(input.includes("stop working")){
console.log("not working")
} else {
console.log("working")
}