spread operator
Published on November 4, 2024
Loading content...
在 JavaScript 中,展开操作符(spread operator)无法处理null
和undefined
值。具体来说,这些值在使用展开操作符时会导致不同的行为:
当尝试使用展开操作符展开null
或undefined
时,会抛出错误,因为这两个值不是可迭代的(iterable)对象。例如:
JavaScriptconsole.log([...undefined]); // TypeError: undefined is not iterable console.log([...null]); // TypeError: null is not iterable
与数组不同,当使用展开操作符对对象进行展开时,如果对象是null
或undefined
,JavaScript 会优雅地处理这一情况,不会抛出错误,而是忽略这些值。例如:
JavaScriptconst foo = {...undefined}; // 结果是 {} const bar = {...null}; // 结果是 {}
在这种情况下,展开操作符不会将null
或undefined
的属性包含在新对象中。
JavaScriptconst 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) }
CODEarray Spread syntax requires ...iterable not be null or undefined {}