简体   繁体   English

检查iOS-为什么未定义此变量?

[英]Checking for iOS - Why is this variable undefined?

I'm trying to change how a page acts depending on which version of iOS the user is visiting on. 我试图根据用户正在访问的iOS版本来更改页面的行为。

Below is what I have: 以下是我所拥有的:

    function iOSversion() {
  if (/iP(hone|od|ad)/.test(navigator.platform)) {
    // supports iOS 2.0 and later: <http://bit.ly/TJjs1V>
    var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
    return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
  }
}

var ver = iOSversion();

if (ver[0] >= 8) {
 alert("using iOS8");
} else if (ver[0] <= 7) {
 alert("using iOS7 or earlier");
}

I'm getting 'TypeError: ver is undefined'. 我收到“ TypeError:ver未定义”。

Am I missing something here? 我在这里想念什么吗?

Thanks 谢谢

When if (/iP(hone|od|ad)/.test(navigator.platform)) { check fails your method returns nothing so it ver is undefined . 如果if (/iP(hone|od|ad)/.test(navigator.platform)) {检查失败,您的方法将不会返回任何内容,因此它的verundefined

function iOSversion() {
  if (/iP(hone|od|ad)/.test(navigator.platform)) {
    // supports iOS 2.0 and later: <http://bit.ly/TJjs1V>
    var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
    return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
  } else {
    return [];  //<-- return an empty array and it will not error. 
  }
}

OR check to see if version has a value before you use if. 或在使用if之前检查版本是否具有值。

var ver = iOSversion();
if (ver) { /* do it */ }

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

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