简体   繁体   English

编写并测试一个接受字符串数组并返回数组中最长单词的函数

[英]Write and test a function that accepts an array of strings and returns the longest word in the array

Example of what the function should output => maxWord(["The", "Albatross", "just", "ate", "your", "lunch"]) => "Albatross" 函数应输出的示例=> maxWord([“ The”,“ Albatross”,“ just”,“ ate”,“ your”,“午餐”])=>“ Albatross”

After looking at other examples of similar problems, I came up with this. 在查看了类似问题的其他示例之后,我想到了这一点。 But it says its an illegal return statement. 但它说这是非法的退货声明。

 function maxWord(string){ var longestWord= arr[0]; for(var i = 0; i < str.length;i++){ word = arr[i]; if(word.length > longestWord.length){ longestWord = word; } } } return word; } 

it's because you have an extra close brace and you have typos in the variables to use. 这是因为您有一个额外的括号,并且要使用的变量中有错别字。

Change your code to be: 将代码更改为:

  function maxWord(arr){
    var longestWord= arr[0];
    for(var i = 0; i < arr.length;i++){
        word = arr[i];
        if(word.length > longestWord.length){
            longestWord = word;
        }

    }
    return longestWord;
}

Here's a fiddle of it working https://jsfiddle.net/qjm4qxwy/ 这是工作的一个小提琴https://jsfiddle.net/qjm4qxwy/

Here's a solution in es6 using Array.reduce 这是es6中使用Array.reduce的解决方案

const maxWord = (words) => {
   return words.reduce((longest, word) => {
     longest = word.length > longest.length ? word : longest;
     return longest;
   }, '')
}

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

相关问题 编写一个接受字符串数组的方法 - Write a method accepts an array of strings 查找数组中最长的单词 - Finding longest word in array 编写一个 function 称为键,它接受 object 并返回 object 中所有键的数组 - Write a function called keys, which accepts an object and returns an array of all of the keys in the object 编写一个域频率“分类”function,它接受 URL 数组并返回预期的 output - Write a Domain frequency 'categorize' function which accepts array of URLS and returns expected output 编写一个 function “giveMeRandom”,它接受一个数字 n 并返回一个包含 n 个介于 0 和 10 之间的随机数的数组 - Write a function “giveMeRandom” which accepts a number n and returns an array containing n random numbers between 0 and 10 编写一个接受字符串数组的方法奇怪词 - Write a method strange_words that accepts an array of strings Function 接受 Array 和 Number 并返回 Number 的第一个索引(如果在 Array 中找到) - Function that accepts an Array and a Number and returns the first index of the Number if found in the Array 查找数组中最长的单词/字符串 - Find the longest word/string in an array 在Javascript数组中查找最长的单词 - Find longest word in Javascript array Javascript:将.sort与compare函数结合使用以查找数组中最长的单词 - Javascript: Using .sort with compare function to find longest word in array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM