简体   繁体   中英

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.

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'.

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 .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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