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

实现endangeredSpecies函数及解决Cannot read property 'length' of undefined报错

解决Cannot read property 'length' of undefined错误并实现濒危物种状态查询功能

首先咱们来拆解你遇到的问题:你看到的Cannot read property 'length' of undefined报错,核心原因是你调用了一个完全没定义的getStatus函数。当代码执行到status = getStatus(div[i].children, species)时,getStatus是undefined,尝试调用它就会抛出这个错误。除此之外,你的代码还有几个其他细节问题需要修正:


问题梳理

  1. 缺失getStatus函数:你在代码里直接调用了这个函数,但根本没写它的定义,这是触发报错的直接原因。
  2. 函数未返回结果:你的endangeredSpecies最后只有console.log(status),没有用return返回状态值,完全不符合需求里“返回濒危状态”的要求。
  3. 测试调用参数不全:你测试时写了endangeredSpecies('North America'),但函数需要两个参数(大陆名和物种名),这会导致species参数为undefined,后续查找逻辑直接失效。
  4. DOM遍历逻辑可以优化:直接遍历div.children不是最简洁的方式,用属性选择器能更精准高效地定位元素。

修正后的完整代码

function endangeredSpecies(continent, species) {
  // 1. 精准定位对应大陆的物种列表
  const continentList = document.querySelector(`ul[data-continent="${continent}"]`);
  
  // 处理找不到大陆的情况
  if (!continentList) {
    return 'Continent not found';
  }
  
  // 2. 在该大陆列表里定位目标物种
  const speciesItem = continentList.querySelector(`li[data-species="${species}"]`);
  
  // 3. 返回状态或找不到物种的提示
  return speciesItem ? speciesItem.textContent.trim() : 'Species not found';
}

// 测试示例
console.log(endangeredSpecies('North America', 'American bison')); // 输出 'Near Threatened'
console.log(endangeredSpecies('Europe', 'Cave bear')); // 输出 'Extinct'
console.log(endangeredSpecies('Asia', 'Giant Panda')); // 输出 'Continent not found'

代码细节解释

  1. 用属性选择器精准定位:
    • document.querySelector(ul[data-continent="${continent}"])直接根据data-continent属性找到对应大陆的列表,比遍历所有子元素效率高得多。
    • 接着用continentList.querySelector(li[data-species="${species}"])在目标大陆的列表里定位具体物种。
  2. 异常情况处理:
    • 如果找不到指定大陆,返回明确的提示文本。
    • 如果大陆存在但找不到对应物种,同样返回提示,避免返回空值或undefined。
  3. 返回结果而非仅打印:用return返回状态文本,完全符合函数的需求设计。

如果你偏好原生循环的实现方式

如果你不想用querySelector,想用循环遍历的方式实现,修正后的代码如下:

function endangeredSpecies(continent, species) {
  const div = document.querySelector('div');
  const ulLists = div.querySelectorAll('ul');
  let status = 'Species not found';

  for (const ul of ulLists) {
    if (ul.dataset.continent === continent) {
      const liItems = ul.querySelectorAll('li');
      for (const li of liItems) {
        if (li.dataset.species === species) {
          status = li.textContent.trim();
          break; // 找到物种后直接跳出内层循环,提升效率
        }
      }
      break; // 找到对应大陆后无需继续遍历其他大陆
    }
  }

  return status;
}

// 测试
console.log(endangeredSpecies('North America', 'California condor')); // 输出 'Critically Endangered'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:01:54