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

如何筛选长度大于5个字符的first字段姓名?代码问题求解

修正方案及代码说明

你的代码存在三个关键问题:

  • 数组方法误用:map 用于转换每个数组元素,但你需要筛选符合条件的元素,应该使用 filter。
  • 拼写错误:lenght 是拼写错误,正确的属性名是 length。
  • 条件判断偏差:要获取长度超过5个字母的姓名,应该判断 length > 5(原代码的 >4 会包含刚好5个字母的姓名,比如 "Albus")。

修正后的代码如下:

const fullNames = [
  { first: "Albus", last: "Dumbledore" },
  { first: "Harry", last: "Potter" },
  { first: "Hermione", last: "Granger" },
  { first: "Ron", last: "Weasley" },
  { first: "Rubeus", last: "Hagrid" },
  { first: "Minerva", last: "McGonagall" },
  { first: "Severus", last: "Snape" },
];

const firstNames = fullNames
  .filter(person => person.first.length > 5)
  .map(person => person.first);

console.log(firstNames); // 输出: ["Hermione", "Rubeus", "Minerva", "Severus"]

代码逻辑说明

  1. filter 阶段:遍历数组,仅保留 first 字段长度大于5的对象。
  2. map 阶段:将筛选后的对象转换为对应的 first 字段值,最终得到只包含符合条件姓名的数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:05:16