javascript - 从字符串JavaScript返回最大3位数字块

我不明白为什么会返回零:


function largestOfThree (num) {


 let stringyNums = num.toString();


 let highest = 0;



 for (let i = 0; i <= stringyNums.length - 3; i++) {


 let chunk = stringyNums.slice(i, i + 3);


 console.log(chunk);


 if (chunk> highest) chunk = highest;


 }


 return highest;


}


console.log(largestOfThree(123456789));

似乎chunk没有被分配给 highest , 我想在'在stringyNums中循环遍历,每次'大于现有highest块的情况下,将新的块分配到最高。

函数应该返回 789,在本例中。

时间:

你没有将 highest 设置为 chunk 更改,


if (chunk> highest) chunk = highest;




if (chunk> highest) highest = chunk ;



因为这一行


if (chunk> highest) chunk = highest;



指定块到最高,而不是指定最大块的最大值, 只要反转这两个变量,你就好了。


if (chunk> highest) highest = chunk;



为了参考,你可以使用oneliner完成此操作:


const largestOfThree = num =>


 num


 . toString()


 . match(/.{1,3}/g)


 . map(Number)


 . reduce((acc, curr) => (acc> curr? acc : curr));



console.log(largestOfThree(123456789));

你在给chunk=highest分配错误


function largestOfThree (num) {



 let stringyNums = num.toString();


 let highest = 0; 


 for (let i = 0; i <= stringyNums.length - 3; i++) {



 let chunk = stringyNums.slice(i, i + 3);


 console.log(chunk);


 if (chunk> highest) highest=chunk; <---the error was here



 }



 return highest;



}



console.log(largestOfThree(123456789));




largestOfThree(num: number): number {


 const stringyNums = num.toString();


 let highest = 0;


 for (let i = 0; i <= stringyNums.length - 3; i++) {


 let chunk = parseInt(stringyNums.slice(i, i + 3));


 if (chunk> highest) highest = chunk;


 }


 return highest;


}



...