uni-app 安卓app不识别 .at(-1)语法
uni-app 安卓app不识别 .at(-1)语法
类别 | 信息 |
---|---|
产品分类 | uniapp/App |
PC开发环境 | Windows |
PC开发环境版本 | win11 |
HBuilderX类型 | 正式 |
HBuilderX版本 | 3.98 |
手机系统 | Android |
手机系统版本 | Android 13 |
手机厂商 | 小米 |
手机机型 | 小米10 |
页面类型 | vue |
vue版本 | vue3 |
打包方式 | 云端 |
项目创建方式 | HBuilderX |
操作步骤:
数组的.at(-1)方法在微信小程序正常,在app中提示错误“value.at is not a function”
预期结果:
正常获取数组的最后一项
实际结果:
报错
bug描述:
3 回复
同样的问题+1
应该不是bug,感觉就是暂时不支持这个
在 UniApp 中,如果你在安卓平台上使用 .at(-1)
语法时遇到问题,可能是因为安卓系统或某些 JavaScript 环境不支持 .at()
方法。.at()
是 ES2022 中引入的新方法,用于通过索引访问数组元素,并支持负数索引(例如 -1
表示最后一个元素)。
解决方案
如果你需要在 UniApp 中兼容不支持 .at()
的环境,可以使用传统的数组访问方式来实现相同的功能。例如:
// 使用 .at(-1) 的等效代码
const array = [1, 2, 3, 4];
const lastElement = array[array.length - 1]; // 等同于 array.at(-1)
console.log(lastElement); // 输出 4
兼容性处理
为了确保代码在所有环境下都能正常运行,你可以封装一个兼容性函数:
function getArrayElement(arr, index) {
if (typeof arr.at === 'function') {
return arr.at(index);
} else {
// 兼容不支持 .at() 的环境
if (index < 0) {
return arr[arr.length + index];
}
return arr[index];
}
}
// 使用示例
const array = [1, 2, 3, 4];
const lastElement = getArrayElement(array, -1);
console.log(lastElement); // 输出 4