查找数组中最短的字符串 [英] Find the shortest string in array

查看:273
本文介绍了查找数组中最短的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在javascript数组中找到具有不同数量的数组元素的最短字符串? 我用

How can i find the shortest string in javascript array with different count of array elements? I used

var min = Math.min(arr[0].length,arr[1].length,arr[2].length);

,我得到的结果像是数组3个元素之间的最短字符串.但我不想关心元素的数量

and i have result like shortest string between 3 elements of array. But I don't want to care about numbers of elements

推荐答案

使用

Use Array#map to create an array of lengths, and then apply it to Math.min():

var arr = ['cats', 'giants', 'daughters', 'ice'];
var min = Math.min.apply(Math, arr.map(function(str) { return str.length; }));
console.log(min);

或使用ES6的数组展开和箭头功能:

Or use ES6's array spread and arrow function:

var arr = ['cats', 'giants', 'daughters', 'ice'];
var min = Math.min(...arr.map(({ length }) => length));
console.log(min);

这篇关于查找数组中最短的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆