【问题标题】:what is the shortest word in this array using function and easy method? [duplicate]使用函数和简单方法的数组中最短的单词是什么? [复制]
【发布时间】:2020-11-07 01:23:23
【问题描述】:

我想在 javascript 中找到这个数组中最短的名称。喜欢

var a = ['john','mahmud','nasimon','Jheather','jo','moon','calibration'];

现在,这个数组中最短的单词是什么? 我想知道初学者的方法。 谢谢。

【问题讨论】:

标签: javascript arrays


【解决方案1】:

询问初学者方法可以遍历所有元素并检查它们的长度并将其添加到变量中。

喜欢:

    let a = ['john','mahmud','nasimon','Jheather','jo','moon','calibration'];
    let shortest = false;

    a.forEach( name => {

         if(!shortest || shortest.length > name.length) shortest = name;
    })

    console.log(shortest)

【讨论】:

    【解决方案2】:

    一种易于理解的方法,使用简单的 for 循环。 请注意,此方法假设没有两个具有相同长度的字符串。如果有两个长度相同的字符串,则打印数组中第一个最短的元素。

    var arr = ['john','mahmud','nasimon','Jheather','jo','moon','calibration'];
    
    function findShortestElem(array){
    
    let minEle = array[0];
    
    for(let i=1;i<array.length;i++){
        
        if(array[i].length<minEle.length){
          minEle = array[i];
        }
    }
    
    return minEle;
    }
    
    console.log(findShortestElem(arr));

    【讨论】:

    • 非常感谢。我只是想要那样的东西。现在我有最后一个问题。你能帮帮我吗?
    • 请告诉我。
    • 请问可以使用功能吗?
    • 你的意思是创建一个接受数组并返回最短元素的函数
    • 是的,先生。这就是我想要的结果。请帮忙
    【解决方案3】:

    如果数组中只有一个最短的字符串,这是减少数组的经典案例。

    Array#reduce 使用累加器(第一个参数)和数组中的值作为第二个参数,并在这种情况下返回较短的字符串。

    如果没有可用的起始值,则采用数组的前两个值。

    const
        array = ['john', 'mahmud', 'nasimon', 'Jheather', 'jo', 'moon', 'calibration'],
        shortest = array.reduce((a, b) => a.length <= b.length ? a : b);
    
    console.log(shortest);

    【讨论】:

      【解决方案4】:

      你可以试试这个

       var a = ['john','mahmud','nasimon','Jheather','jo','moon','calibration'];
           var len=a.map(n=>n.length) //first get the names lenghts 
           var min=Math.min(...len)//use the Math class to get the minimum number 
           var result=a.find(name=>name.length==min) //find the name and match the length
            console.log(result)

      【讨论】:

        猜你喜欢
        • 2019-07-31
        • 2016-09-04
        • 1970-01-01
        • 2019-08-17
        • 2022-08-13
        • 2022-01-21
        • 1970-01-01
        • 2022-01-24
        • 2021-11-11
        相关资源
        最近更新 更多