2016-05-20 55 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