gpt4 book ai didi

javascript - 列表中最短的单词 - JS

转载 作者:行者123 更新时间:2023-11-30 07:54:10 25 4
gpt4 key购买 nike

我需要返回三个列表中最短的单词。如果有关系,它应该返回参数列表中的第一个单词。

到目前为止,这是我的功能:

function short(w1, w2, w3) {
var arr = word1.concat(word2, word3);
arr.split(",");

arr.reduce(function(a, b) {
return a.length <= b.length ? a : b;
});
}

var output = short('a', 'bee', 'gracele');
console.log(output); // --> MUST RETURN 'a'

现在这个不行。知道我错过了什么吗?

最佳答案

您已经接近您所写的内容,但您犯了一些错误。

首先,您尝试使用 wordword2word3。没有一个是定义的。我假设这是一个打字错误,您实际上是指 w1w2w3

其次,您尝试连接单词并在 , 上拆分,但您没有在字符串中添加逗号。

最后,您不会返回 reduce 函数调用的结果。

解决这些问题,通过将函数 arguments 立即转换为数组来简化流程,您将拥有:

function short(/* any number of args */) {
var words = [].slice.call(arguments);

return words.reduce(function (a, b) {
return a.length <= b.length ? a : b;
});
}

结合@JaredFarrish 建议的想法,您可以修改函数以接受单个单词或单词数组。

function short(words) {
words = Array.isArray(words) ? words : [].slice.call(arguments);

return words.reduce(function (a, b) {
return a.length <= b.length ? a : b;
});
}

console.log(short('this', 'is', 'a', 'sentence')); // 'a'
console.log(short('this is a sentence'.split(' '))); // 'a'

关于javascript - 列表中最短的单词 - JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44712085/

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