开发者问题收集

使用 javascript 计算缺失数组的长度

2019-03-09
1707

我正在尝试解决 CodeWars 上缺少数组的长度问题。 这是我的代码。

function getLengthOfMissingArray(arr) {
  let result = 0;

  if (arr === null || arr.length === 0) return 0;

  arr = arr.sort((a, b) => b.length - a.length);
  console.log(arr)

  for (let i = 0; i < arr.length; i++) {

    if (arr[i].length === 0 || arr[i] === null) return 0;

    else if (arr[i].length - arr[i + 1].length !== 1) {
      console.log(arr[i].length);
      console.log(arr[i + 1].length);

      result = arr[i].length - 1;
    }
  }
  return result;
}


console.log(getLengthOfMissingArray([
  [5, 2, 9],
  [4, 5, 1, 1],
  [1],
  [5, 6, 7, 8, 9]
]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

问题是我不断收到 TypeError:无法读取未定义的属性“length”console.log(arr[i + 1].length) 运行正常,显示 arr[i + 1].length 为 1。我对此真的很困惑。有人能帮我吗?谢谢!

TypeError: Cannot read property 'length' of undefined
    at getLengthOfMissingArray (/home/chrx/Documents/codeWars/Length of missing array.js:8:45)
    at Object.<anonymous> (/home/chrx/Documents/codeWars/Length of missing array.js:19:17)
    at Module._compile (internal/modules/cjs/loader.js:734:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:745:10)
    at Module.load (internal/modules/cjs/loader.js:626:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:566:12)
    at Function.Module._load (internal/modules/cjs/loader.js:558:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:797:12)
    at executeUserCode (internal/bootstrap/node.js:526:15)
    at startMainThreadExecution (internal/bootstrap/node.js:439:3)
3个回答

您的主要问题是在执行循环的最后一次迭代时下一行的数组索引溢出:

else if (arr[i].length - arr[i + 1].length !== 1)

特别是在评估此代码时: arr[i + 1].length

但是,我对您的代码做了一些额外的修复,它们在代码中进行了解释:

function getLengthOfMissingArray(arr)
{
    // Check for all safe conditions at the start.

    if (!Array.isArray(arr) || arr.length === 0)
        return 0;

    if (arr.some(innerArr => !Array.isArray(innerArr)))
        return 0;

    // Sort mutates the array, there is no need to save it
    // again on arr variable.

    arr.sort((a, b) => b.length - a.length);

    // Start looping: to "arr.length - 1" maximum.

    for (let i = 0; i < arr.length - 1; i++)
    {
        // If find the missing length, return here, don't keep iterating.
        if (arr[i].length - arr[i + 1].length !== 1)
            return arr[i].length - 1;
    }
}

console.log("[Good Test] Missing length: ", getLengthOfMissingArray([
  [5, 2, 9],
  [4, 5, 1, 1],
  [1],
  [5, 6, 7, 8, 9]
]));

// Check samples with errors:

console.log("[Bad Test 1] Missing length: ", getLengthOfMissingArray(null));

console.log("[Bad Test 2] Missing length: ", getLengthOfMissingArray([]));

console.log("[Bad Test 3] Missing length: ", getLengthOfMissingArray([
  [5, 2, 9],
  "what?",
  [1],
  [5, 6, 7, 8, 9]
]));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Shidersz
2019-03-09

显示错误的原因是它溢出了数组。 添加对 arr[i + 1] 的检查应该有效。

if (!arr[i].length || !arr[i]|| !arr[i + 1]) return 0;
Loc Mai
2019-03-09

您循环到最后一个元素,但在循环中访问下一个元素(i+1),这意味着它将溢出,因为最后一个元素之后没有元素,因此会产生未定义的错误。

如果您打算在循环中访问下一个元素(i+1),您应该只循环到最后一个元素之前的一个元素(arr.length - 1)。

这是工作代码。

function getLengthOfMissingArray(arr) {
  let result = 0;

  if (arr === null || arr.length === 0) return 0;

  arr = arr.sort((a, b) => b.length - a.length);
  console.log(arr)

  // here is my only addition: loop upto a element before last element.
  for (let i = 0; i < arr.length-1; i++) {

    if (arr[i].length === 0 || arr[i] === null) return 0;

    else if (arr[i].length - arr[i + 1].length !== 1) {
      console.log(arr[i].length);
      console.log(arr[i + 1].length);

      result = arr[i].length - 1;
    }
  }
  return result;
}


console.log(getLengthOfMissingArray([
  [5, 2, 9],
  [4, 5, 1, 1],
  [1],
  [5, 6, 7, 8, 9]
]));
Gianfranco Fertino
2019-03-09