+ 2
Pls help me troubleshoot this code. I want to write the JavaScript equivalent of a Python function
The function takes a sentence as argument and returns the longest word. JavaScript (pls check the JS tab for my code): https://code.sololearn.com/WcbNVaVkabwW/?ref=app This is how it should work (Python): https://code.sololearn.com/clz157k6uDhM/?ref=app
4 ответов
+ 6
Maybe your JS interpreter doesn't support the '...' operator of the parameter of the rest ^^
You can rather normally use the .apply() method of Function prototype:
Math.max.apply(null,list)
... should works ;)
(but be sure you doesn't ommit a closing parenthesis or such syntax/typo error :P)
+ 6
/*
Your first mistake is to use your 'i' index iterator as the item of the list... access to the item is done by:
arrayName[index]
Second mistake is in use of Math.max() method: arguments are not allowed to be directly passed as an array... but fortunaly, you can pass an array as an argument list, with the operator 'parameter of the rest':
Math.max(...arrayName):
Third non blocking mistake: the unnecessary use of the 'break' statement...
*/
// fixed code:
function longest(string) {
var list = [];
var splitString = string.split(" ");
for(var i = 0; i < splitString.length; i++) {
list.push(splitString[i].length);
}
for (var i = 0; i < splitString.length; i++) {
if (splitString[i].length == Math.max(...list)) {
return splitString[i];
// break // unnecessary, return is a form of radical break ^^
}
}
}
alert(longest("This is the longest sentence I've never seen..."));
+ 1
Thanks. A lot.
Math.max.apply(null, list) worked.
0
Thanks @visph. I've corrected the errors. However, now I'm getting a syntax error (error message references the line containing Math.max).
I ran the code using both ScriptIt and AIDE Web on a tablet.