JavaScript中从API请求的对象数组使用filter方法无效的原因
问题分析与解决方案
核心错误原因
sentence是一个Promise对象,不是数组,直接调用filter方法必然报错——只有数组拥有filter方法,Promise没有该方法。- 你的
map写法存在问题:data.map((e) => { e.title})中的花括号没有返回值,等价于每个元素都返回undefined,即便拿到结果也不是你需要的内容。 - 错误地将Promise对象塞进数组再调用
Promise.all,属于异步流程处理混乱,完全是多余操作。
修正后的代码
用async/await写法(可读性更强)
async function titles(word) { const api = 'https://jsonplaceholder.typicode.com/posts'; // 等待请求完成并解析为JSON数组 const response = await fetch(api); const posts = await response.json(); // 直接对数组过滤,返回标题包含指定单词的项 return posts.filter(post => post.title.includes(word)); } // 使用示例: titles('ipsum').then(result => console.log(result));
用Promise链式写法(不依赖async/await)
function titles(word) { const api = 'https://jsonplaceholder.typicode.com/posts'; return fetch(api) .then(res => res.json()) .then(posts => posts.filter(post => post.title.includes(word))); } // 使用示例: titles('ipsum').then(result => console.log(result));
代码优化建议
- 优先用
async/await替代嵌套then链,代码逻辑更清晰,可读性更高。 - 移除冗余变量(比如原代码中的
array、sentence),直接在异步流程中处理数据,减少不必要的内存占用。 - 添加错误处理,避免请求失败时抛出未捕获错误,增强代码健壮性:
async function titles(word) { const api = 'https://jsonplaceholder.typicode.com/posts'; try { const response = await fetch(api); if (!response.ok) { throw new Error(`请求失败:${response.status}`); } const posts = await response.json(); return posts.filter(post => post.title.includes(word)); } catch (error) { console.error('处理请求时出错:', error); return []; // 出错时返回空数组,避免调用方崩溃 } }
内容的提问来源于stack exchange,提问作者Luis Daniel Arciniegas Barco
相关产品推荐
相关产品推荐

