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

使用JavaScript的find方法查找数组中含'e'的首个及全部元素

解决方法

首先你的代码存在两个关键问题:

  • 数组定义的变量是fruits,但你错误使用了未定义的words变量
  • 回调函数里的判断逻辑alpha == words完全偏离需求,这是在把数组元素和整个数组做相等比较,根本不会检查元素是否包含字母'e'

1. 查找第一个包含字母'e'的元素

使用Array.find()方法,回调函数里通过String.includes()判断当前字符串是否包含目标字母:

const fruits = ['apple', 'banana', 'cherry', 'dates', 'fig'];
const firstMatch = fruits.find(fruit => fruit.includes('e'));
console.log(firstMatch); // 输出: apple

2. 查找所有包含字母'e'的元素

find()只能返回第一个匹配项,要获取所有符合条件的元素,需要用Array.filter():

const fruits = ['apple', 'banana', 'cherry', 'dates', 'fig'];
const allMatches = fruits.filter(fruit => fruit.includes('e'));
console.log(allMatches); // 输出: ['apple', 'cherry', 'dates']

额外说明

  • find()遍历数组时,会返回第一个满足条件的元素,无匹配项则返回undefined
  • filter()会返回所有满足条件的元素组成的新数组,无匹配项则返回空数组
  • includes()是ES6新增的字符串方法,用于判断字符串是否包含指定子串,兼容性覆盖绝大多数现代浏览器

内容的提问来源于stack exchange,提问作者Abd.al

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 23:37:33