JavaScript函数没有返回正确的值

时间:2011-12-28 09:31:46

标签: javascript

我正在开发一个函数,我想检查当前正在使用哪个useragent 以下代码只是一个原型,它返回它首先读取的任何值 - 在本例中为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());
}

我不知道出了什么问题。也许你们可以看到它并告诉我在哪里做错了。

3 个答案:

答案 0 :(得分:6)

如果找不到匹配项,

indexOf会返回-1。如果找到匹配项,则返回的值是找到的子字符串的字符索引。

要检查子字符串是否存在,您应该使用:

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

答案 1 :(得分:2)

return (browser.indexOf('IE') > -1)
           ? "Internet Explorer" 
           : (browser.indexOf('Mozilla') > -1)
                ? "FireFox" 
                : "UserAgent not recognized!";

答案 2 :(得分:0)

您没有检查索引的值......

如果你发现indexOf('IE')> = 0应该是你的行......

相关问题