JS返回一个字符串中长度最小的单词的长度

  题目:编写一个方法,返回字符串中最小长度的单词的长度。

  var str = 'What a good day today!';
 1 //方法一
 2 function returnString1(str){
 3     var arr = str.split(' ');
 4     var num = [];
 5     // console.log(arr);
 6     for(var i=0,len=arr.length; i<len; i++){
 7         // console.log(arr[i].length);
 8         num.push(arr[i].length);
 9     }
10     num.sort(sortNum);
11     return num.shift();
12 }
13 function sortNum(a, b){
14     if(a > b){
15         return 1;
16     }else if(a < b){
17         return -1;
18     }else {
19         return 0;
20     }
21 }
22 console.log(returnString1(str));
 1 //方法二
 2 function returnString2(str){
 3     var num = 0;
 4     var arr = str.split(" ");
 5     arr.forEach(function(item,i){
 6         if(i === 0){
 7             num = item.length;
 8         }else{
 9             if(item.length<num){
10                 num = item.length;
11             }
12         }
13     });
14     return num;
15 }
16 console.log(returnString2(str));
1 //方法三
2 function returnString3(str){
3     return Math.min.apply(null, str.split(' ').map(w => w.length));
4 }
5 console.log(returnString3(str));

猜你喜欢

转载自www.cnblogs.com/SophiaLees/p/9378529.html