在使用 map 方法时,在遇到 undefined 或 null 值时需要加以判断处理。这是因为 map 方法会在数组中的每个元素调用回调函数,如果元素值为 undefined 或 null,则会抛出错误。以下是示例代码:
const array = [1, 2, null, 4, undefined, 6];
// 如果数组中含有 undefined 或 null 值,需要进行处理
const newArray = array.map((value) => {
if (value === undefined || value === null) {
return 0; // 或者其他的默认值
}
return value * 2;
});
console.log(newArray); // [2, 4, 0, 8, 0, 12]
上述示例代码中,通过判断数组元素是否为 undefined 或 null,然后返回该元素值或者一个默认值,避免了 map 方法因调用 undefined 或 null 值而出错的情况。