应使用正则/(\d+)\.(\d+)/i提取主次版本号并转数字,先判断platform再解析,未匹配时设默认值0,避免字典序比较错误和nan。

uni.getSystemInfoSync().system 返回的字符串怎么安全提取版本数字
直接对 system 字段做字符串比较(比如 "iOS 17.5" > "iOS 15")会出错,因为这是字典序比较,“iOS 9” > “iOS 15” 成立。必须先提取主次版本号再转数字。
实操建议:
- 用正则
/(\d+)\.(\d+)/提取前两位数字,忽略平台前缀和小数点后更多位(如 17.5.1 → 取 17 和 5) - 务必加
i标志兼容大小写不一致(某些安卓 WebView 可能返回android 14,iOS 模拟器可能返回ios 16.4) - 先判断
platform再解析,避免安卓匹配到system里的数字误当 iOS 版本 - 没匹配到时设默认值(如
0),防止parseInt(undefined)得NaN
示例代码片段:
const sys = uni.getSystemInfoSync()
const isIOS = sys.platform === 'ios'
let major = 0, minor = 0
if (isIOS) {
const match = sys.system.match(/iOS\s+(\d+)\.(\d+)/i)
if (match) {
major = parseInt(match[1], 10)
minor = parseInt(match[2], 10)
}
}
if (major
<h3>Android <a style="color:#f60; text-decoration:underline;" title="系统版本" href="https://m.php.cn/zt/46340.html" target="_blank">系统版本</a>号为什么经常拿不准</h3>
<p>安卓端 <code>system</code> 字段虽常为 <code>"Android 14"</code>,但 OEM 厂商(尤其华为、小米、vivo)普遍篡改或屏蔽底层系统属性,导致真机返回空、乱码或硬件代号(如 <code>"Android ELE-AL00"</code>)。这不是 <a style="color:#f60; text-decoration:underline;" title="uni-app" href="https://m.php.cn/zt/15764.html" target="_blank">uni-app</a> 的 bug,是系统层限制。</p>
<p>实操建议:</p>
- 不要依赖
system做精确判断,它只适合粗略分档(如是否 ≥ Android 11) - 需要强约束时(例如调用某 Android 12+ 新 API),优先查
plus.os.version(需 HBuilderX 3.9+,且仅在原生环境有效) - 降级方案:结合
screenWidth和screenHeight判断是否为折叠屏/大屏设备,间接推测系统能力 - 测试阶段务必用多台真机验证,模拟器返回值不可信
如何判断当前环境是否支持某项系统能力(而非只看版本号)
版本号只是代理指标,真正要解决的是“这个 API 能不能用”。比如 iOS 14+ 才支持 WKWebView 的 allowsInlineMediaPlayback,但用户可能通过越狱或降级绕过系统版本限制。
实操建议:
- 优先用特性检测(feature detection)代替版本检测(version detection)
- 对关键 API,先
typeof plus.webview.currentWebview.setBounce === 'function'再调用 - 对 Web API(如
IntersectionObserver、ResizeObserver),用if ('IntersectionObserver' in window)判断 - 对原生能力(如蓝牙、NFC),用
plus.bluetooth?.isSupported()或plus.nfc?.isSupported(),比查系统版本更可靠
冷启动 vs 热更新后获取的 system 值为什么不一致
H5 和小程序环境里 uni.getSystemInfoSync() 是模拟值,model 恒为 "browser";App 端热更新(wgt 包)后,部分字段(尤其是 system)可能被缓存或未刷新,导致拿到旧值。
容易踩的坑:
- 在
onShow里直接读system,结果拿到的是上一次冷启动时的缓存值 - 未加
#ifdef APP条件编译,H5 环境报plus is not defined - 真机调试时不清除 App 数据,旧 SDK 缓存了错误的
system字符串
正确做法:冷启动(onLaunch)时读一次并存入 uni.setStorageSync('sys_info', sys),后续都从 storage 读;热更新后主动触发一次重新采集(可配合 plus.runtime.restart() 后重置)。











