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

JavaScript Fetch API循环遇null值终止 如何跳过对应索引继续执行?

错误原因

你遇到的报错是因为判断逻辑顺序错误:当房源没有主图时,data.properties[i].primary_photo本身就是null,此时你直接访问null.href会直接抛出类型错误,根本不会执行后续的=== null判断。


修复方案

你需要先校验primary_photo是否存在,再读取它的href属性,最简单的方式是使用ES6可选链操作符?.做安全访问,修改后的判断逻辑如下:

// 先判断primary_photo存在,再判断href不为空
if (!data.properties[i].primary_photo?.href) {
  continue;
}

如果需要兼容不支持可选链的旧环境,可以写成分层判断:

const currentProperty = data.properties[i];
// 先校验primary_photo不是null/undefined,再校验href有值
if (!currentProperty.primary_photo || !currentProperty.primary_photo.href) {
  continue;
}

优化后完整代码

以下代码额外解决了「固定遍历前12条、跳过无图后最终渲染卡片不足12张」的问题,会自动遍历返回数据直到凑齐12张有效带图卡片:

fetch(`https://real-estate12.p.rapidapi.com/listings/sale?state=CA&city=San%20Francisco&page=1&sort=relevant&type=single-family%2Cmulti-family`, {
  "method": "GET",
  "headers": {
    "x-rapidapi-host": "real-estate12.p.rapidapi.com",
    "x-rapidapi-key": "removingAPIkeyforStackOverflow"
  }
})
.then(function (response) {
  return response.json();
})
.then(function (data) {     
  houseCardsEl.innerHTML = '';
  let renderCount = 0;
  // 遍历所有返回数据,直到渲染满12张有效卡片
  for (let i = 0; i < data.properties.length && renderCount < 12; i++) {
    const currentHouse = data.properties[i];
    // 安全校验,无图则跳过
    if (!currentHouse.primary_photo?.href) {
      continue;
    }
    houseCardsEl.innerHTML += 
      `<div id="column-${renderCount}" class="column is-one-quarter">
        <div class="card">
          <div class="card-image">
            <figure id="houseImage" class="image is-4by3">
              <img src="${currentHouse.primary_photo.href}" alt="House image ${renderCount}">
            </figure>
          </div>
        </div>
      </div>`;
    renderCount++;
  }
})
.catch(err => {
  console.error(err);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:54:08