2016-05-20 56 views
-2

我希望有人可以提供帮助。我已经看过堆栈中的JavaScript示例,但可以使用下面的语句来工作。当添加OR语句时发生错误。有人可以帮助语法?与我们的代码Javascript IF和OR语句

if ((this.drawX >= CANVAS_WIDTH - this.width && this.isRightKey==true) 
    || (this.drawX <= 0 - this.width && this.isLeft Key==true)) 

    { 
    this.speed = 0; 
    } 

    else { 
    this.speed =5; 
    } 

问题:

if (this.drawX >= CANVAS_WIDTH - this.width && this.isRightKey) 
    || ((this.drawX <= -this.width && this.isLeftKey) { 
    this.speed = 0; 
} else { 
    this.speed = 5; 
} 
+0

看来你的条件语法是错误的。试试这个:if((this.drawX> = CANVAS_WIDTH - this.width && this.isRightKey == true) ||(this.drawX <= 0 - this.width && this.isLeft Key == true)) ' – dlopez

+0

你好像在'isLeft'和'Key'之间有一个空格,这是错误的。你不必检查一个布尔值== true。根据定义,这只是真的或假的。 – ManoDestra

回答

1

试试这个

1. odd no of `(` , ie. brackets are not closed properly 

2. wrong position of || condition . 

3. this.isLeft Key , space issue 
0

你的括号关闭。 if中的整个条件应该用圆括号包围。为了提高知名度,这是不是一个坏主意来包装||的每一个分支用括号太:

if ((this.drawX >= CANVAS_WIDTH - this.width && this.isRightKey==true) || 
    (this.drawX <= 0 - this.width && this.isLeft Key==true)) { 
     // code comes here... 
0

至于其他的答案中提到的问题与您的代码,我想回答我的。您可以简化这个多为:

var bool = (this.drawX >= CANVAS_WIDTH - this.width && this.isRightKey === true) || 
      (this.drawX <= 0 - this.width && this.isLeftKey === true); 

this.speed = bool ? 0 : 5; // <=== condition ? true : false; 

现在在你的代码的问题:

  1. 缺少(开,如果条件和)关闭也和你有一个(在一个位置,它不需要。
  2. this.isLeft Key单词之间有空格。
+0

谢谢大家,所有解决方案都完美无缺! – stckpete

+0

我在这个答案中怀疑所有其他的解决方案,按照第2点。 – Jai