2015-11-16 31 views
-1

我有下面的代碼部分:爲什麼不工作條件?

var SocketChat = socketFactory({ 
       ioSocket: (typeof io === 'undefined') ? io.connect('http://test.com:8181') : null 
      }); 

我嘗試檢查是否存在io對象爲:

(typeof io === 'undefined') 

,但我得到的錯誤ReferenceError: io is not defined仍然

+0

讀[這](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) – Lucius

回答

1

讓我們寫的是三元聲明:

(typeof io === 'undefined') ? io.connect('http://test.com:8181') : null 

基本上是:

if(typeof io === 'undefined'){ 
    io.connect('http://test.com:8181')} 
} else { 
    null; 
} 

所以,如果ioundefined,你想打電話.connect就可以了。

這是行不通的。

你可能想改變你的病情:

io ? io.connect('http://test.com:8181') : null 

所以,如果io是truthy值,.connect叫就可以了。

+0

你都錯了:'(typeof運算IO ===未定義')? << ---' – Muhad

+0

我怎麼錯了?那裏有什麼問題? – Cerbrus

+0

它應該是'!=='undefined'' – Muhad

0

如果ioundefined,怎麼io.connect()應該工作?請更改您的代碼:

(typeof io === 'undefined') ? null: io.connect('http://test.com:8181') 
1

使用條件正確的方式,如何訪問io.connect如果io未定義??

var SocketChat = socketFactory({ 
        ioSocket: (typeof io !== 'undefined') ? io.connect('http://test.com:8181') : null 
       });