寻找最长的&JavaScript中最短的单词 [英] Finding Longest & Shortest word in JavaScript

查看:80
本文介绍了寻找最长的&JavaScript中最短的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题之一是要查找字符串中最长的单词&另一个是找到字符串中最短的单词.

One of the question is to find longest word in a string & another one is to find the shortest word in a string.

我试图找出解决它们之间的区别.我了解所有内容,但为什么将longestlength设为"longestlength = 0"而不是"longestlength = newString [0] .length".我试图用它解决它,并且输出是不确定的.同样,对于"shortestLength",如果我将其初始化为"0"而不是"newString [0] .length",则无法定义,但我不理解其背后的原因.

I am trying to figure out the difference between solving them. I understand everything except why is "longestlength =0" for the longestlength instead of "longestlength = newString[0].length." I tried solving it with that and the output is undefined. Likewise, for the "shortestLength" if I initialize it with "0" instead of "newString[0].length" I get undefined but I don't understand the reason behind it.

//code for longest string

 function longestWord(string) { 
let newString =string.split(" ");
let longestWord;
let longestlength= 0;
for(let i=0; i<newString.length; i++){
if(newString[i].length > longestlength){
  longestlength = newString[i].length;
  longestWord= newString[i];
 }
  }
 return longestWord;
  }

 //code for shortest string
  function shortestWord(string) {
 var stringArray = string.split(" ");  
  var shortestWord;
  var shortestLength = stringArray[0].length; 
  for(var i = 0; i < stringArray.length; i++){
   if(stringArray[i].length < shortestLength){
  shortestLength = stringArray[i].length;   
  shortestWord = stringArray[i];            
  }
    }
return shortestWord;
  }

推荐答案

您可以使用 reduce 一步解决您的问题.

Your problem can be solved in one line using reduce.

最长的单词:

string.split(' ').reduce((acc, cur) => acc.length >= cur.length ? acc : cur);

最短的单词:

string.split(' ').reduce((acc, cur) => acc.length <= cur.length ? acc : cur);

这是您的代码无法正常工作的原因:在 shortestWord 中,您将当前的最短长度设置为数组中第一个单词的长度,但您没有这样做将最短单词设置为数组中的第一个单词,但仍未定义.如果数组中的第一个单词恰好是最短的单词,则没有哪个单词会更短,因此将没有单词分配给 shortestWord ,并且该函数将返回 undefined .

Here's why your code might not work: In shortestWord, you set the current shortest length to the length of the first word in the array, but you don't set the shortest word to the first word in the array, it is still undefined. If the first word in the array happens to be the shortest word, no word is shorter, therefore no word will ever be assigned to shortestWord and the function will return undefined.

解决方案:替换

var shortestWord;

使用

var shortestWord = stringArray[0];

这篇关于寻找最长的&amp;JavaScript中最短的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆