gpt4 book ai didi

javascript - 返回最短单词和最长单词的长度差值(使用 for 循环)

转载 作者:行者123 更新时间:2023-12-05 09:35:37 25 4
gpt4 key购买 nike

我想知道如何返回最短单词和最长单词的长度差值(使用 for 循环):

function findShort(s){

s = s.split(" ");

(for let i = 0; i < s.length; i++) {
******code goes here******
}

}

findShort("bitcoin take over the world maybe who knows perhaps");
findShort("turns out random test cases are easier than writing out basic ones");
});

有什么想法吗?如果有人也想尝试使用 map 或 reduce 之类的东西,我们也将不胜感激。

干杯!

最佳答案

将数组缩减为一对 shortlong 值,并返回差值:

const findDelta = str => {
const [long, short] = str.split(/\s+/)
.reduce(([long, short], { length }) => [
Math.max(long, length), // take the longest length
Math.min(short, length) // take the shortest length
], [-Infinity, Infinity]) // init long with -Infinity and short with Infinity

return long - short
}

console.log(findDelta("bitcoin take over the world maybe who knows perhaps"))
console.log(findDelta("turns out random test cases are easier than writing out basic ones"))

关于javascript - 返回最短单词和最长单词的长度差值(使用 for 循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65743000/

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