使用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()遍历数组时,会返回第一个满足条件的元素,无匹配项则返回undefinedfilter()会返回所有满足条件的元素组成的新数组,无匹配项则返回空数组includes()是ES6新增的字符串方法,用于判断字符串是否包含指定子串,兼容性覆盖绝大多数现代浏览器
内容的提问来源于stack exchange,提问作者Abd.al
相关产品推荐
相关产品推荐

