gpt4 book ai didi

javascript - 获取最长的单词 - JS

转载 作者:行者123 更新时间:2023-11-29 19:03:38 29 4
gpt4 key购买 nike

我正在编写一个返回给定数组中最长字符串的函数。如果数组为空,它应该返回一个空字符串 ("")。如果数组不包含字符串;它应该返回一个空字符串。

function longestWord(arr) {
var filtered = arr.filter(function(el) { return typeof el == 'number' });
if (filtered.length > 0) {
return Math.min.apply(Math, filtered);
} else {
return 0;
}
}

var output = longestWord([3, 'word', 5, 'up', 3, 1]);
console.log(output); // --> must be 'word'

现在我的代码不会提取单词,而是提取数字。知道我错过了什么吗?

最佳答案

让我们浏览一下您的代码。

longestWord 函数的第一行:

var filtered = arr.filter(function(el) { return typeof el == 'number' });

将根据 typeof el === 'number' 过滤输入数组,这将返回一个仅包含输入数组元素的数组,这些元素是 type of === number

由于目标是找到最长的单词,因此应该将其更改为:

var filtered = arr.filter(function(el) { return typeof el === 'string' });

这将返回输入数组中的字符串数组。

接下来,检查过滤后的数组是否为空。如果数组为空,则返回 0。你的说明说如果数组为空,或者如果数组不包含字符串,它应该返回一个空字符串。所以我们应该将其更改为:

return "";

如果数组不为空,或包含字符串,则返回 Math.min.apply(Math, filtered)。该语句将返回数组的最小值,因此可能不是您想要的。毕竟,目标是返回最长的字符串。

为此我们可以使用多种方法,这里是一个:

filtered.reduce(function(a, b) { return a.length > b.length ? a : b })

此语句使用 reduce()方法遍历数组并返回最长的项目。

综合起来我们得到:

function longestWord(arr) {
var filtered = arr.filter(function(el) { return typeof el === 'string' });
if (filtered.length > 0) {
return filtered.reduce(function(a, b) { return a.length >= b.length ? a : b });
} else {
return "";
}
}

console.log(longestWord([3, 'word', 5, 'up', 3, 'testing', 1]));
console.log(longestWord([]));
console.log(longestWord([1, 2, 3, 4, 5]))
console.log(longestWord(['some', 'long', 'four', 'char', 'strs']))

关于javascript - 获取最长的单词 - JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44689935/

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