zoukankan      html  css  js  c++  java
  • 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));
    一个人静静地坐在电脑前写代码,有种武林高手闭关修炼的感觉!
  • 相关阅读:
    CSS---伪类
    CSS---选择器
    CSS---如何引用样式表
    HTML-- 表单
    HTML-- 文本标签
    HTML--连接、锚点
    HTML--表格
    递归算法
    PHPCMS V9 友情链接的调用
    thinkcmf跳转用户登录和个人中心页面时出现Call to undefined function sp_sql_posts()错误
  • 原文地址:https://www.cnblogs.com/SophiaLees/p/9378529.html
Copyright © 2011-2022 走看看