[英]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.