不知道为什么这个JS函数中有这么多-1

时间:2018-09-18 09:03:43

标签: javascript

我想知道什么'A!= B? true:false'代表。还有,为什么这句话中有这么多-1?

getBrowser: function() {
    if (null == this.browserName) {
        var a = navigator.userAgent.toLowerCase();
        f("[getBrowser()] navigator.userAgent.toLowerCase() -> " + a); - 1 != a.indexOf("msie") && -1 == a.indexOf("opera") ? this.browserName2 = this.browserName = "MSIE" : -1 != a.indexOf("iphone") ? (this.browserName = "Netscape Family", this.browserName2 = "iPhone") : -1 != a.indexOf("firefox") && -1 == a.indexOf("opera") ? (this.browserName = "Netscape Family", this.browserName2 = "Firefox") : -1 != a.indexOf("chrome") ? (this.browserName = "Netscape Family", this.browserName2 = "Chrome") : -1 != a.indexOf("safari") ? (this.browserName = "Netscape Family", this.browserName2 = "Safari") : -1 != a.indexOf("mozilla") && -1 == a.indexOf("opera") ? (this.browserName = "Netscape Family", this.browserName2 = "Other") : -1 != a.indexOf("opera") ? (this.browserName = "Netscape Family", this.browserName2 = "Opera") : (this.browserName = "?", this.browserName2 = "unknown");
        f("[getBrowser()] Detected browser name:" + this.browserName + ", " + this.browserName2)
    }
    return this.browserName
},

1 个答案:

答案 0 :(得分:1)

在JavaScript中,?:用于表示ternary operator,它实际上是if/else语句,但是是以另一种形式编写的。 所以,这:

if (condition) {
    stuff_if_true();
} else {
    stuff_if_false();
}

与此等效:

condition ?
    stuff_if_true() :
    stuff_if_false()

documentation的说法是,“ indexOf()方法返回指定值首次出现的调用String对象内的索引,从fromIndex开始搜索。如果值是-1​​,则返回-1。 “。因此,在您提供的代码中,只有一些使用三元运算符编写的嵌套if / else语句。他们实际上正在测试a变量中某些子字符串(chrome,opera等)的存在。

转换为if / else的代码将是:

if (a.indexOf("msie") !== -1 && -1 === a.indexOf("opera")) {
    this.browserName2 = this.browserName = "MSIE"
} else if (-1 !== a.indexOf("iphone")) {
    this.browserName = "Netscape Family";
    this.browserName2 = "iPhone";
} else if (-1 !== a.indexOf("firefox") && -1 === a.indexOf("opera")) {
    this.browserName = "Netscape Family";
    this.browserName2 = "Firefox";
} else if (-1 !== a.indexOf("chrome")) {
    this.browserName = "Netscape Family";
    this.browserName2 = "Chrome";
} else if (-1 !== a.indexOf("safari")) {
    this.browserName = "Netscape Family";
    this.browserName2 = "Safari";
} else if (-1 !== a.indexOf("mozilla") && -1 === a.indexOf("opera")) {
    this.browserName = "Netscape Family";
    this.browserName2 = "Other";
} else if (-1 !== a.indexOf("opera")) {
    this.browserName = "Netscape Family";
    this.browserName2 = "Opera";
} else {
    this.browserName = "?";
    this.browserName2 = "unknown";
    f("[getBrowser()] Detected browser name:" + this.browserName + ", " + this.browserName2)
}

您可能还会感到困惑,因为在大多数情况下,您会看到状态符号为a.indexOf("iphone") !== -1而不是-1 !== a.indexOf("iphone")(它们只是切换了,但在这里含义相同)。

干杯!