admin管理员组文章数量:1353303
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. 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?
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. 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?
Share Improve this question edited Sep 19, 2018 at 18:14 G Cadogan 1821 silver badge9 bronze badges asked Sep 19, 2018 at 18:08 SoXSoX 431 silver badge6 bronze badges 2-
1
arr[i]>longest
should bearr[i].length>longest.length
– Luis felipe De jesus Munoz Commented Sep 19, 2018 at 18:09 -
Compare the
length
property in yourif
condition instead of paring string. – Mohammad Usman Commented Sep 19, 2018 at 18:10
3 Answers
Reset to default 4You 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
.
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.
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])
本文标签: javascriptFind longest string in arrayStack Overflow
版权声明:本文标题:javascript - Find longest string in array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743861440a2551809.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论