为什么这篇文章没有在下面的例子中编译?
“|| this.greeting != "test2"
”
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
setGreeting(g) {
this.greeting = g;
}
test() {
if(this.greeting != "test" || this.greeting != "test2"){
//this.greeting cound still be test3
}
}
}
Link to example
最佳答案
这实际上是一个有效的错误,并防止你犯错误。
if (this.greeting != "test" || this.greeting != "test2") {
因为您使用的是
||
,所以除非this.greeting == 'test'
,否则不会执行第二个条件。现在,它非常聪明,可以在输入第二个条件块时自动输入
this.greeting
cc。显然,
'test'
永远不会是错误的,检查这个条件可能是错误的,因为您的整个'test' != 'test2'
语句总是返回true。你可能想写:
if (this.greeting != "test" && this.greeting != "test2") {