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

时间:2019-04-22 19:19:02

标签: javascript string for-loop numbers

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

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

5 个答案:

答案 0 :(得分:4)

您没有将highest设置为chunk 更改

if (chunk > highest) chunk = highest;

收件人

if (chunk > highest) highest = chunk ;

答案 1 :(得分:3)

是因为这一行

if (chunk > highest) chunk = highest;

您正在将块分配给最高块,而不是将最大块分配给最大块。只需反转两个变量,就可以了。

if (chunk > highest) highest = chunk;

答案 2 :(得分:2)

作为参考,您可以使用更具可读性的单线形式(6-线吗?)来完成此操作:

const largestOfThree = num =>
  num
  .toString()
  .match(/.{1,3}/g)
  .map(Number)
  .reduce((acc, curr) => (acc > curr ? acc : curr));

console.log(largestOfThree(123456789));

答案 3 :(得分:1)

尝试一下。您正在分配错误的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));

答案 4 :(得分:1)

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;
}