JavaScript如何显示数组中长度最短的名称
在JavaScript中找出数组里最短的名称
给定数组:
let friends = ['Alfonso Waters', 'Mona', 'Mania','Mona Dunn', 'Mae','Mae Lane']
方法一:获取第一个出现的最短名称(高效遍历一次)
用reduce方法遍历数组,每次比较当前元素和已记录的最短元素的长度,更新最短元素:
const shortestName = friends.reduce((shortest, current) => { return current.length < shortest.length ? current : shortest; }, friends[0]); console.log(shortestName); // 输出:Mae
方法二:获取所有最短名称(处理多个同长度的情况)
如果数组里有多个长度相同的最短名称,先算出最短长度,再过滤出所有符合条件的元素:
// 计算最短名称的长度 const minLength = Math.min(...friends.map(name => name.length)); // 过滤出所有长度等于最短长度的名称 const allShortestNames = friends.filter(name => name.length === minLength); console.log(allShortestNames); // 输出:["Mae"]
处理空数组的情况
如果数组可能为空,记得加判断避免报错:
let friends = []; let shortestName; if (friends.length > 0) { shortestName = friends.reduce((shortest, current) => { return current.length < shortest.length ? current : shortest; }, friends[0]); } else { console.log("数组为空,无法找到最短名称"); }
内容的提问来源于stack exchange,提问作者Ahmed Daud
相关产品推荐
相关产品推荐

