我想知道如何返回最短单词和最长单词的长度差值(使用 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 之类的东西,我们也将不胜感激。
干杯!
最佳答案
将数组缩减为一对 short
和 long
值,并返回差值:
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/