解决forEach循环中if-else语句导致“未找到设备”错误
"devices.forEach((device: any) \u003d\u003e {\n\t\tif (device.deviceId === mac) {\n\t\t\twx.stopBluetoothDevicesDiscovery({\n\t\t\t\tsuccess: (res) \u003d\u003e {\n\t\t\t\t\tthis.connectBlueTooth(device.deviceId);\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tcommonUtils.showToast('未找到设备');\n\t\t}\n\t})"\n\n报forEach没有找到是怎么回事内容:报错是因为在forEach循环中使用了if-else语句,但是在if语句中判断条件为false时,会执行else语句。而根据代码逻辑,只有当找到对应的设备时,才执行if语句中的代码,否则应该提示"未找到设备"。所以报错提示"forEach没有找到"是因为在循环中没有找到匹配的设备时,执行了else语句,但是没有返回或抛出异常,导致报错。\n\n要修复这个问题,可以将else语句移动到forEach循环结束后执行,判断是否找到设备的逻辑可以使用一个变量来标记。示例代码如下:\n\njavascript\nlet foundDevice = false;\n\ndevices.forEach((device: any) \u003d\u003e {\n\tif (device.deviceId === mac) {\n\t\twx.stopBluetoothDevicesDiscovery({\n\t\t\tsuccess: (res) \u003d\u003e {\n\t\t\t\tthis.connectBlueTooth(device.deviceId);\n\t\t\t}\n\t\t});\n\t\tfoundDevice = true;\n\t}\n});\n\nif (!foundDevice) {\n\tcommonUtils.showToast('未找到设备');\n}\n\n\n这样修改后,当找到对应设备时,执行if语句中的代码,并将foundDevice标记为true;循环结束后,判断foundDevice的值,如果为false,则提示"未找到设备"。
原文地址: https://www.cveoy.top/t/topic/pH45 著作权归作者所有。请勿转载和采集!