如何在 JavaScript 中捕获数组索引越界?

Cod*_*ack 3 javascript error-handling try-catch

我想在发生数组边界之外的访问时捕获错误,但它似乎不会抛出错误。

let arr = [2,4,5];
let test = arr[3];
console.log(test);
Run Code Online (Sandbox Code Playgroud)

我知道我可以测试未定义并抛出错误

if (arr[3] === undefined) throw new Error();
Run Code Online (Sandbox Code Playgroud)

但为什么我不能像下面这样尝试并抓住它。

let arr = [2,4,5];
try {
      let tmp = arr[3];
    } catch(e) {
      lastIndex = findLastIndex(arr, high / 2, high);
      break;
    }
Run Code Online (Sandbox Code Playgroud)

Sno*_*now 8

正如您所看到的,访问不存在的数组索引不会引发错误 - 值“accessed”将只是undefined。普通对象的工作方式相同:

const obj = {};
// No error:
const val = obj.foo;

console.log(val);
Run Code Online (Sandbox Code Playgroud)

但错误通常不应该用于控制流 - 错误应该处理异常情况。对于你正在做的事情,我会使用if/else代替,例如

const arr = [0, 1, 2];
if (4 in arr) {
  const val = arr[4];
  // ...
} else {
  console.log('4 is not in the arr');
}
Run Code Online (Sandbox Code Playgroud)