function LongestWord(sen) {
let arr = sen.split(' ');
let longestWord;
for (let i = 0; i < arr.length; i++) {
let counter = 0;
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
};
该函数的目的是循环遍历一个数组并找到最长的单词。我一直在仔细检查,似乎一切正确,但是,显然有问题,但我没有看到。
答案 0 :(得分:2)
这是因为您在每次迭代中都将count设置为零,即重写为
function LongestWord(sen) {
let arr = sen.split(' ');
let longestWord;
let counter = 0; // Moved here!!!
for (let i = 0; i < arr.length; i++) {
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
};
答案 1 :(得分:2)
我知道这是一种完全不同的方法,但是您可以使用以下更简洁的代码获得相同的结果,而无需应用任何循环结构:
function LongestWord(sen) {
let arr = sen.split(' ');
return arr.sort(function(a, b){
// Sort Descending
return b.length - a.length;
})[0]; // Take first and longest element
}
答案 2 :(得分:1)
您要在每次迭代时重新声明计数器。
function LongestWord(sen) {
let arr = sen.split(' ');
let longestWord;
let counter = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
};
答案 3 :(得分:1)
您需要在厕所之外定义计数器,因为您需要使用它来保持长度
function longestWord(sen) {
let arr = sen.split(' ');
let longestWord;
let counter = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
}
console.log(longestWord('orange banana potatoe hackfleischbällchen rice'))
答案 4 :(得分:1)
您需要使用for循环之外的计数器。因为每次使用in for循环时都要重新初始化它。
function LongestWord(sen) {
let arr = sen.split(' ');
let longestWord;
let counter = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
};
console.log(LongestWord('heya 1 2'))
答案 5 :(得分:1)
function LongestWord(sen) {
let arr = sen.split(' ');
let longestWord;
let counter = 0; // you need to place counter outside for loop
for (let i = 0; i < arr.length; i++) {
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
};
console.log(LongestWord('something is wrong with this'));
答案 6 :(得分:0)
这样的事情怎么样
# cat longest_word.js
function longestWord(str) {
return str.split(' ').reduce(function (acc, word) {
return acc.length > word.length ? acc : word;
});
}
console.log(longestWord('the quick brown fox jumps over the lazy dog'));
# node longest_word.js
jumps
#