2015-11-16 30 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 
       });