比较数组中字符串的长度?

Comparing length of strings in an array?

您好,我正在尝试比较句子中每个单词的长度。我将这句话转换成一个数组,但后来我迷失在我的代码中。 我尝试了 2 种方法 - for loop 和 reduce(),但都没有用。我的代码发生了什么?

Reduce() => 当我尝试 运行 函数时,这个给了我未定义的。我收集它是因为 max.length/word.length,但是如何使用 reduce() 将我的字符串转换为长度?

function findLongestWordLength(str) {
  let brokenDown = str.split(' ')
  
  brokenDown.reduce((max, word) => {
    return Math.max(max.length, word.length)
  })
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");

For 循环 => 这个给了我第一个单词的长度而不是 maxLength。我猜可能是因为我的 var strLength 不是一个数组,但是如何将它变成一个包含每个索引长度的数组?

function findLongestWordLength(str) {
  let brokenDown = str.split(' ')
  for(let i = 0; i < brokenDown.length; i++) {
    var strLength = brokenDown[i].length
  }
  return Math.max(strLength)
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");

我知道这应该是非常基本和简单的,我无法理解这里出了什么问题。

const maxLength = (str) => {
  const words = str.split(' ');
  const lengths = words.map((word) => word.length);
  return Math.max(...lengths);
}
console.log(maxLength('The quick brown fox jumped over the lazy dog'));

在您发布的第二种方法中,您没有正确设置最大值。您正在设置一个名为 strLength 的变量,但您的 Math.max 在循环之外。所以你永远不会得到最大值,除非它恰好是数组中的最后一个单词。

function findLongestWordLength(str) {
  let brokenDown = str.split(' ')
  let mxLen = 0
  for(let i = 0; i < brokenDown.length; i++) {
    mxLen = Math.max(mxLen, brokenDown[i].length);
  }
  return mxLen
}

如果您想使用 Math.max 方法,首先提取每个单词的长度,然后将其传递给 Math.max

function findLongestWordLength(str) {
  let brokenDown = str.split(' ')
  let lengths = brokenDown.map(word => word.length);

  return Math.max(...lengths);
}

console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));


如果您想使用 for 循环方法,您必须在循环时保持 maxLength,并在循环遇到更长的单词时更新它。

function findLongestWordLength(str) {
  let brokenDown = str.split(' ')
  let maxLength = 0;
  for (let i = 0; i < brokenDown.length; i++) {
    const wordLength = brokenDown[i].length;
    if (wordLength > maxLength) {
      maxLength = wordLength;
    }
  }
  return maxLength;
}

console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));

不难做到...

const findLongestWordLength = str =>
  str.split(' ').reduce((r,s)=>Math.max(r,s.length), 0)



console.log( findLongestWordLength("The quick brown fox jumped over the lazy dog") )