JS-找出字符串中的最长单词

264 阅读1分钟

题目

返回给出的句子中,最长单词的长度。

函数的返回值应是一个数字。

我的思路:

将字符串转为数组,数组内每个元素是字符串,遍历数组,将每个字符串的长度存储到一个新的数组中。

求出新数组中的最大数组,返回即可。

代码如下:

function findLongestWordLength(str) {
  let arr = str.split(' ');
  let newArr = [];
  arr.forEach((item, index) => {
    newArr[index] = item.length
  })
  let max = newArr.reduce((key1, key2) => {
    return key1 > key2 ? key1 : key2;
  })
  return max;
}

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