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

标签 javascript arrays string for-loop string-length

我想知道如何返回最短单词和最长单词的长度差值(使用 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/

相关文章:

javascript - 通过链接使用 Rails 和 Javascript 复制到剪贴板

javascript - AngularJS - 如何在自定义指令中更改 ngModel 的值?

javascript - 将字符串数组从 ajax 函数传递到 mvc Controller

javascript - 更新状态时无法在现有状态转换期间更新?

c - 基于 GCC 的 SIGSEGV 错误?

c# - 替换字符串中的某个子字符串 - .Replace() 方法对我不起作用 C#

javascript - 为什么无法在 TypeScript 中导出类实例?

javascript - Highcharts : Venn Diagram how to show total and union numbers?

javascript - 将 HTMLCollection 转换为数组的最有效方法

Java - 替换单引号而不影响多个单引号