javascript - 返回 JavaScript 中字符串中最短单词的长度

标签 javascript arrays algorithm function

<分区>

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

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() 返回一个数字而不是 bool 值。 sort() 函数应该是:

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

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

关于javascript - 返回 JavaScript 中字符串中最短单词的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56815010/

相关文章:

algorithm - 找到给定几条对角线的所有多边形面

javascript - 使用 regExp 将字符串中的多个单词动态匹配到另一个单词

javascript - NodeJS 服务器 "swallows" header 字段

javascript - 获取随机数并关注限制(抛物线)

c - 从所有数组元素打印字符串

python - 检查以确保字符串不包含多个值

javascript - 来自 PHP : how to get a dynamically generated javascript image

jquery - 如何在 JavaScript 中合并两个带有嵌套数组的对象?

java - 在java中将字符数组的程序更改为字符串需要经过哪些步骤?

algorithm - 从句子中提取食物