简体   繁体   English

查找数组中最长的字符串

[英]Find longest string in array

I'm supposed to find the longest string in an array, but can't find what's wrong with my code. 我应该在数组中找到最长的字符串,但是找不到我的代码出了什么问题。 Something isn't working when trying to debug in Visual Studio Code it just won't detach. 尝试在Visual Studio Code中进行调试时,某些操作不起作用,只是无法分离。 Please help me with what's wrong! 请帮我解决问题!

Code: 码:

let arr = ["Orebro", "Sundsvall", "Hudriksvall", "Goteborg"];

function long_string(arr){
   let longest="";
   for (let i=0;i<arr.length;i++){
      if (arr[i]>longest){
         longest=arr[i];
      }
   } 
   return longest;
}

long_string(arr)

Can anyone spot the mistake? 谁能发现错误?

You need to check the length of the item and the stored longest string. 您需要检查项目的长度和存储的最长字符串。

if (arr[i].length > longest.length) {
//        ^^^^^^^          ^^^^^^^

Just another hint, you could use the first item as start value for longest and start iterating from index 1 . 另一个提示是,您可以将第一项用作longest起始值,并从索引1开始迭代。

 function long_string(arr) { let longest = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i].length > longest.length) { longest = arr[i]; } } return longest; } let arr = ["Orebro", "Sundsvall", "Hudriksvall", "Goteborg"]; console.log(long_string(arr)); 

You can use reduce method for this and check length of current string in each iteration. 您可以为此使用reduce方法,并在每次迭代中检查当前字符串的长度。

 let arr = ["Orebro", "Sundsvall", "Hudriksvall", "Goteborg"]; let result = arr.reduce((r, e) => r.length < e.length ? e : r, ""); console.log(result) 

Another way to to it would be sorting and getting the first item 另一种方法是排序并获取第一项

 let arr = ["Orebro", "Sundsvall", "Hudriksvall", "Goteborg"]; console.log(arr.sort((a,b)=>b.length-a.length)[0]) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM