返回JavaScript中字符串中最短单词的长度 [英] Returning the length of the shortest word in a string in JavaScript

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

问题描述

我正在尝试编写一个函数,该函数返回字符串中最短单词的长度.它仅在某些时间有效,我似乎无法弄清楚为什么.

I'm trying to write a function that returns the length of the shortest word in a string. It only works some of the time and I can't seem to figure out why.

function findShort(s) {
  const stringArray = s.split(" ");

// Compares the length of two words, then moves to the next till complete.
// Returns the words in order of length 
  const orderedArray = stringArray.sort((a, b) => {
    return a.length > b.length;
  })
  //returns the length of the first word(0 index of array) 
  return orderedArray[0].length;

}

推荐答案

您需要从 sort()返回一个数字,而不是布尔值. sort()函数应为:

You need to return a number from sort() not a boolean. The sort() function should be:

const orderedArray = stringArray.sort((a, b) => {
   return a.length - b.length;
})

function findShort(s) {
  const stringArray = s.split(" ");
  const orderedArray = stringArray.sort((a, b) => {
    return a.length - b.length
  })
  return orderedArray[0].length;

}
console.log(findShort("The quick brown fox ju map"))

您不需要对整个数组进行 sort()只需使用 map()来获取长度数组,然后将其传递给 Math.min

You don't need to sort() the whole array just use map() to get array of lengths and then pass it to Math.min

const findShort = str => Math.min(...str.split(' ').map(x => x.length))
console.log(findShort("The quick brown fox ju map"))

这篇关于返回JavaScript中字符串中最短单词的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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