我有一个JSON数组-Level1>>Level2>>Level3。Level1将具有所有操作系统名称,如Windows、Linux等。对于每个操作系统,我们都有级别2阵列,每个类别下都有操作系统和版本。对于ex.windows 10 64位在级别2中,我们有用户代理列表。我们必须将浏览器用户代理与JSON中的userAgent列表相匹配,并显示为检测到的操作系统。我的代码-
matchTheOSVersionWithUserAgent: function (osVersion){
var userAgentList = osVersion.userAgent;
var matchRes;
for(i in userAgentList){
matchRes = navigator.userAgent.match(userAgentList[i]);
}
mock JSON:
osPlatforms: [{
"name": "Windows",
"osVersions": [{
"name": "Windows 10 (32 bit)",
"osBit": "32",
"userAgent": ["Windows 10 (32 bit)", "win10", "Microsoft Windows 10", "Windows NT 10.0", "Microsoft Windows 10 (64-bit)"],
}, {
"name": "Windows 10 (64 bit)",
"osBit": "64",
"userAgent": ["win10", "Microsoft Windows 10", "Windows NT 10.0", "Microsoft Windows 10 (32-bit)"],
}]
我将matchedRes设置为null,并且没有进行检测。我试着登录mac和windows。有人能帮我吗。TIA。
您需要这样做:
var osPlatforms = [{
"name": "Windows",
"osVersions": [{
"name": "Windows 10 (32 bit)",
"osBit": "32",
"userAgent": ["Windows 10 (32 bit)", "win10", "Microsoft Windows 10", "Windows NT 10.0", "Microsoft Windows 10 (64-bit)", "Windows NT 6.1"],
}, {
"name": "Windows 10 (64 bit)",
"osBit": "64",
"userAgent": ["win10", "Microsoft Windows 10", "Windows NT 10.0", "Microsoft Windows 10 (32-bit)"],
}]
}];
function matchTheOSVersionWithUserAgent(osVersion) {
console.log(navigator.userAgent);
var userAgentList = osVersion.userAgent;
var matchRes;
for (var i = 0; i < userAgentList.length; i++) {
if (navigator.userAgent.match(userAgentList[i])) {
matchRes = navigator.userAgent.match(userAgentList[i]);
break;
}
}
console.log(matchRes);
}
matchTheOSVersionWithUserAgent(osPlatforms[0].osVersions[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
基本上,一旦找到结果,break
循环。