不要在特定输入上做任何事情

问题描述 投票:0回答:1
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 workingworking,它也会记录x,然后记录false。并且只有在为working时才应记录为真。

javascript
1个回答
1
投票

问题出在这里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") 
}
© www.soinside.com 2019 - 2024. All rights reserved.