Last updated on

spread operator

在 JavaScript 中,展开操作符(spread operator)无法处理nullundefined值。具体来说,这些值在使用展开操作符时会导致不同的行为:

对于数组展开

当尝试使用展开操作符展开nullundefined时,会抛出错误,因为这两个值不是可迭代的(iterable)对象。例如:

console.log([...undefined]); // TypeError: undefined is not iterable
console.log([...null]);      // TypeError: null is not iterable

对于对象展开

与数组不同,当使用展开操作符对对象进行展开时,如果对象是nullundefined,JavaScript 会优雅地处理这一情况,不会抛出错误,而是忽略这些值。例如:

const foo = {...undefined}; // 结果是 {}
const bar = {...null};      // 结果是 {}

在这种情况下,展开操作符不会将nullundefined的属性包含在新对象中。

验证

const und = undefined
const nul = null

try {
    const array = [...nul, ...und]
    console.log(array)
} catch (error) {
    console.log("array", error.message)
}

try {
    const obj = { ...nul, ...und }
    console.log(obj)
} catch (error) {
    console.log("obj", error.message)
}
array Spread syntax requires ...iterable not be null or undefined
{}