gpt4 book ai didi

arrays - JS 如何在数组中查找字符串中最长的单词

转载 作者:行者123 更新时间:2023-12-04 02:27:51 26 4
gpt4 key购买 nike

这可能有些尴尬,但我真的是 JS 的新手,在被接受参加 BootCamp 之前,他们问我这个练习,其中包括在数组中的字符串中找到最长的单词。

['The Soviet Union', 'The Consomol', 'United States'] 应该返回 Consomol。

我已经尝试了好几个小时的冲浪,但我只看到了如何获得最长的单词或最长的字符串,但我的兴趣是如何获得数组中给定短语中的最长单词。我写了这段代码...

function longest_string(str_ara) {
var max = str_ara[0].length;
str_ara.map(v => max = Math.max(max, v.length));
result = str_ara.filter(v => v.length == max);
return result;
}

上面的代码给出了最长的字符串,而不是数组中最长的单词。我想要一种添加方法来找到最长的单词。谢谢

最佳答案

希望我正确理解了这个问题 - 否则让我知道..

如果您还需要进一步的解释,请告诉我

const items = ['The Soviet Union', 'The Consomol', 'United States'];

let longestWord = '';

// Loop through every item in the array
items.forEach((item) => {

// Let's split it by space ex. 'The Soviet Union' === ['The', 'Soviet', 'Union']
const words = item.split(" ");

// Loop through each word in the new array
words.forEach((word) => {
// Check if current word is longer than the one we already saved
if (word.length > longestWord.length) {
// If longer - let's update
longestWord = word
}
});
});

// All done - let's output the longest word
console.log(longestWord)

编辑:

要将它用作函数,您可以这样做:

const wordArray = ['The Soviet Union', 'The Consomol', 'United States'];

function extractLongestWord(items) {
let longestWord = '';
items.forEach((item) => {
const words = item.split(" ");
words.forEach((word) => {
if (word.length > longestWord.length) {
longestWord = word
}
});
});

return longestWord;
}

console.log(extractLongestWord(wordArray))

关于arrays - JS 如何在数组中查找字符串中最长的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66182435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com