You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法检测或提取API返回JSON数组中的内容?

问题分析与解决方案

核心问题

你遇到的includes()不生效,本质是逻辑分支判断错误,而非Promise pending状态(你已经用await response.json()拿到了实际的数组)。具体问题出在这几个地方:


1. isEmpty函数无返回值,导致判断逻辑失效

你的isEmpty函数仅做了控制台输出,没有返回布尔值。当执行if(!isEmpty())时,isEmpty()默认返回undefined,!undefined等于true,所以永远会进入第一个分支,else if的代码根本不会执行。

修正isEmpty函数,让它返回判断结果:

const isEmpty = () => {
  const value = searchedKeyword.value.trim(); // 处理输入首尾空格
  const empty = value === '';
  empty ? console.log('Empty - try categories:') : console.log('Not empty');
  return empty; // 必须返回布尔值供判断使用
};

2. 逻辑分支顺序错误

原代码的分支逻辑搞反了:应该先判断输入是否为空,为空则提示;不为空再检查是否在数组中。

修正getCategories里的判断逻辑:

async function getCategories() {
  try {
    const response = await fetch(apiEndpointCategories);
    if (!response.ok) {
      alert('Oops, try again!');
      throw Error(response.statusText);
    }
    const categories = await response.json(); // 变量名更语义化
    const inputValue = searchedKeyword.value.trim().toLowerCase(); // 统一小写,避免大小写不匹配

    if (isEmpty()) {
      console.log('可用分类:', categories);
    } else if (categories.includes(inputValue)) {
      console.log('Cool - 匹配到分类!');
    } else {
      console.log('未找到匹配的分类'); // 补充未匹配的提示
    }
  } catch (err) {
    console.log('请求错误:', err);
    alert('请求失败,请稍后重试'); // 替换不存在的summonAlert方法
  }
}

3. 额外优化点

  • 给输入值做trim()和toLowerCase()处理:避免用户输入空格或大小写不一致导致匹配失败
  • 变量名语义化:把json改成categories,代码可读性更强
  • 修复catch块错误:summonAlert()不是Error对象的内置方法,直接用alert做错误提示即可

关于Promise pending的疑问

你已经用await response.json()等待了Promise完成,所以categories(原json)是已经解析完成的数组,不是pending状态。可以通过console.log(typeof categories, categories)确认它的类型和内容。

内容的提问来源于stack exchange,提问作者Szpotu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 10:55:21