简体   繁体   English

JavaScript函数未返回正确的值

[英]JavaScript function doesn't return correct value

I'm developing a function in which I'd like to check which useragent is currently being used. 我正在开发一个函数,其中我想检查当前正在使用哪个useragent。
The following code is just a prototype and it returns whatever value it reads first - in this case IE . 以下代码只是一个原型,它返回首先读取的任何值-在这种情况下为IE

detectDevice = function () {
    var userAgent = {
        detect: function () {
            return navigator.userAgent;
        },
        detectBrowser: function () {
            var browser = userAgent.detect();
            var currentBrowser;
            return currentBrowser = browser.indexOf('IE') ? "Internet Explore" : browser.indexOf('Mozilla') ? "FireFox" : "UserAgent not recognized!";
        },
        version: function (identifier) {
        }
    };

    alert(userAgent.detectBrowser());
}

I can't tell what's wrong. 我不知道怎么了。 Maybe you guys can see it and tell me where I made a wrong turn. 也许你们可以看到它,并告诉我我转错了哪里。

indexOf returns -1 if no match is found. 如果找不到匹配项, indexOf返回-1 If a match is found, the returned value is the character index of the found substring. 如果找到匹配项,则返回的值是找到的子字符串的字符索引。

To check whether a substring exists, you should use: 要检查是否存在子字符串,应使用:

browser.indexOf('IE') != -1
// If a match is found, a non-negative index is returned. So, this also works:
//..... indexOf('IE') > -1
// .... indexOf('IE') >= 0
return (browser.indexOf('IE') > -1)
           ? "Internet Explorer" 
           : (browser.indexOf('Mozilla') > -1)
                ? "FireFox" 
                : "UserAgent not recognized!";

You are not checking the value of the index... 您没有检查索引的值...

if you find the indexOf('IE') >= 0 hould be your line... 如果您发现indexOf('IE')> = 0应该是您的行...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM