//项目中使用
export default {
data() {
return {
arr: [] //定义的空数组,存放获取到的对象
};
},
methods: {
//开始搜寻附近的蓝牙外围设备
startBluetoothDevicesDiscovery() {
this.arr = []; //每次搜索前清空列表
uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true, //允许重复上报同一设备,便于动态显示信号值
complete: res => {
//监听寻找到新设备的事件
uni.onBluetoothDeviceFound(result => {
//遍历数组中的对象
result.devices.forEach(item => {
//检索key值为deviceId的数据是否存在,不存在则将遍历出的item对象添加到arr数组中,存在则更新除deviceId之外的对象
ArrDupRem(this.arr, item, 'deviceId');
});
});
//搜索15秒后,主动停止搜索释放系统资源
setTimeout(() => {
uni.stopBluetoothDevicesDiscovery();
}, 15000);
}
});
}
}
};
//封装去重函数
function ArrDupRem(a, o, k) {
let i = a.findIndex(v => v[k] === o[k]);
if (a.findIndex(v => v[k] === o[k]) !== -1) { a.splice(i, 1, o); } else { a.push(o); }
return a;
}
个人笔记,可供新手小白参考,大佬勿喷