获取数组JavaScript中最长和最短的字符串
我们有这样的字符串文字数组-
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a', 'sentence.'];
我们需要编写一个函数,该函数返回该数组中最长和最短的单词。我们将使用Array.prototype.reduce()方法通过完整的迭代来跟踪数组中最长和最短的单词。
为此的代码将是-
示例
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',
'sentence.'];
const findWords = (arr) => {
return arr.reduce((acc, val) => {
const { length: len } = val;
if(len > acc['longest']['length']){
acc['longest'] = val;
}else if(len < acc['shortest']['length']){
acc['shortest'] = val;
};
return acc;
}, {
longest: arr[0],
shortest: arr[0]
});
};
console.log(findWords(arr));输出结果
控制台中的输出将为-
{ longest: 'sentence.', shortest: 'a' }热门推荐
10 登上舞台祝福语大全简短
11 八十大寿简短祝福语
12 老年 生日祝福语大全简短
13 白日庆典祝福语简短英语
14 婚礼西装祝福语简短男士
15 优秀男士祝福语大全简短
16 养生祝福语女生短句简短
17 浪漫的生日祝福语简短
18 公司28 周年祝福语简短