MST

星途 面试题库

面试题:JavaScript中处理数组元素读取错误

在JavaScript中,当尝试读取一个数组中不存在的索引位置的元素时,会返回什么?请举例说明如何在代码中检测并处理这种情况,以避免潜在的错误影响后续逻辑。
46.0万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
  1. 返回值:在JavaScript中,当尝试读取一个数组中不存在的索引位置的元素时,会返回 undefined。例如:
const arr = [1, 2, 3];
console.log(arr[5]); // 返回 undefined
  1. 检测与处理
    • 使用 typeof 检测
const arr = [1, 2, 3];
const value = arr[5];
if (typeof value === 'undefined') {
    // 处理不存在的情况,例如设置默认值
    const defaultValue = 0;
    const actualValue = value === undefined? defaultValue : value;
    console.log(actualValue);
}
  • 使用 Array.isArray 结合索引范围检测
function getSafeValue(arr, index) {
    if (Array.isArray(arr) && index >= 0 && index < arr.length) {
        return arr[index];
    } else {
        return '默认值';
    }
}
const arr = [1, 2, 3];
const result = getSafeValue(arr, 5);
console.log(result);