或者gate(||)将false排序为undefined

时间:2014-03-17 16:47:01

标签: javascript boolean switch-statement gate

我有这样的代码:

var IFS =
    document.isFullScreen || 
    document.webkitIsFullScreen || 
    document.mozIsFullScreen || 
    document.msIsFullScreen;

确切的问题是||网关将false排序为undefined,因为isFullScreen是布尔值。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

如果每个元素都未定义,那么IFS将是未定义的。由于undefined是一个假值,您仍然可以将条件语句作为:

var IFS =
    document.isFullScreen || 
    document.webkitIsFullScreen || 
    document.mozIsFullScreen || 
    document.msIsFullScreen;

if(!IFS){
    console.log('not full screen');
}

如果您仍希望保留false值以防其他变量为undefined,那么您可以选择以下内容:

var IFS =
    document.isFullScreen || 
    document.webkitIsFullScreen || 
    document.mozIsFullScreen || 
    document.msIsFullScreen || 
    false;

答案 1 :(得分:0)

undefined falsey 值,这意味着||运算符将转换为与false相同的值。

如果您只是想找到未定义的第一个值,您可以尝试这样的事情:

var IFS =
    (typeof document.isFullScreen != "undefined") ? document.isFullScreen :
    (typeof document.webkitIsFullScreen != "undefined") ? document.webkitIsFullScreen :
    (typeof document.mozIsFullScreen != "undefined") ? document.mozIsFullScreen :
    (typeof document.msIsFullScreen != "undefined") ? document.msIsFullScreen : 
    false;

Niet suggests

var IFS =
    ('isFullScreen' in document) ? document.isFullScreen :
    ('webkitIsFullScreen' in document) ? document.webkitIsFullScreen :
    ('mozIsFullScreen' in document) ? document.mozIsFullScreen :
    ('msIsFullScreen' in document) ? document.msIsFullScreen : 
    false;

或者您可以使用数组,如下所示:

var arr = ['isFullScreen', 'webkitIsFullScreen', 'mozIsFullScreen', 'msIsFullScreen'];
var IFS = false;
for (var i = 0; i < arr.length; i++) {
    if (arr[i] in document) {
        IFS = document[arr[i]];
        break;
    }
}

或者像这样

var arr = ['isFullScreen', 'webkitIsFullScreen', 'mozIsFullScreen', 'msIsFullScreen'];
var key = arr.filter(function(e) { return e in document; })[0];
var IFS = !!document[key];