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

从JSON对象生成的数组调用join()/toString()无输出问题

解决数组转字符串无输出的问题

问题根源

  1. 循环次数不合理:你当前循环20次,每次push两个元素,最终生成40个元素,但实际有效食材仅10组(20个元素),后续元素全为空字符串,大量空值拼接后看起来像空输出。
  2. 硬编码索引不可靠:依赖measureList[9+i]和measureList[29+i]的写法完全绑定Object.values()的返回顺序,而对象属性的遍历顺序在不同环境可能不稳定,且API返回的食材和分量是成对命名的(如strMeasure1对应strIngredient1),硬编码索引极易出错。
  3. 未过滤空值:当索引超出有效范围时,取到的是undefined或空字符串,这些值在join时会被转为空字符串,直接导致最终结果无效。

修正后的代码

$.ajax({
  method: 'GET',
  url: buildApiUrl({
    query: 'lookup',
    value: 52850,
  }),
}).then(response => {
  const meal = response.meals[0];
  const ingredList = [];

  // 遍历API支持的最多20组食材
  for (let i = 1; i <= 20; i++) {
    const measure = meal[`strMeasure${i}`];
    const ingredient = meal[`strIngredient${i}`];
    // 仅添加非空的有效食材条目
    if (measure && ingredient) {
      ingredList.push(measure, ingredient);
    }
  }

  const result = ingredList.join(' ');
  console.log(result);
});

关键修正点

  • 直接通过命名规范的属性名获取分量和食材,彻底摆脱对Object.values()顺序的依赖,逻辑更可靠。
  • 仅保留非空的有效条目,避免数组混入大量空值。
  • 循环范围控制在API标准的20组食材内,自动停止于无有效数据的位置。

另外补充:你之前注释的循环代码中,key = '.strMeasure' + i多了一个.,正确写法应为strMeasure${i},这也是之前尝试push失败的原因之一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:20:50