如何在JavaScript对象中查找匹配值?代码实现咨询
嘿,我帮你定位到了代码里的核心问题,并且整理了修正后的实现方案:
问题根源
你在使用filter方法时犯了一个典型错误——没有利用回调函数的参数来访问当前遍历的航班对象,反而直接引用了整个flight数组。这样一来,你的筛选逻辑根本不会遍历数组里的每个元素,自然得不到正确的匹配结果。
修正后的XMLHttpRequest实现
let flightInfo = { userInputFlightNumber: 'KL856' }; const xhr2 = new XMLHttpRequest(); const url2 = 'https://api.myjson.com/bins/11uvvr'; xhr2.onreadystatechange = function() { if (xhr2.readyState === XMLHttpRequest.DONE) { // 先确认请求成功 if (xhr2.status === 200) { try { const timetableData = JSON.parse(xhr2.response); // 提前校验数据结构,避免后续报错 if (Array.isArray(timetableData.response.flight)) { // 这里用flightItem指代当前遍历的单个航班对象 const resultArray = timetableData.response.flight.filter(function(flightItem) { return flightItem.iata_number === flightInfo.userInputFlightNumber; }); console.log('匹配到的航班:', resultArray); // 在这里写你对匹配结果的后续处理逻辑 } else { console.error('接口返回的flight不是数组格式'); } } catch (parseErr) { console.error('JSON解析失败:', parseErr); } } else { console.error('请求失败,状态码:', xhr2.status); } } }; // 别忘了打开请求并发送 xhr2.open('GET', url2); xhr2.send();
几个关键的修正细节:
- 正确使用filter回调参数:用
flightItem代表数组中当前正在检查的航班,这样才能逐个对比iata_number。 - 增加错误处理:包括请求状态校验、JSON解析异常捕获、数据格式校验,避免代码因为意外情况直接崩溃。
- 代码可读性优化:给变量起了更清晰的名字,比如把
converTimetableToObject改成timetableData。
更简洁的Fetch API替代方案
如果你的运行环境支持现代浏览器特性,用Fetch API会让代码更简洁易维护:
const flightInfo = { userInputFlightNumber: 'KL856' }; const url = 'https://api.myjson.com/bins/11uvvr'; fetch(url) .then(response => { if (!response.ok) { throw new Error(`请求出错:${response.status}`); } return response.json(); }) .then(timetableData => { if (Array.isArray(timetableData.response.flight)) { const resultArray = timetableData.response.flight.filter(flightItem => flightItem.iata_number === flightInfo.userInputFlightNumber ); console.log('匹配到的航班:', resultArray); // 后续处理逻辑写在这里 } else { console.error('接口返回的flight数据格式不符合预期'); } }) .catch(error => console.error('整体流程出错:', error));
内容的提问来源于stack exchange,提问作者stevv
相关产品推荐
相关产品推荐

