我不了解对象内部的传播语法 [英] I don't understand about spread syntax inside objects
问题描述
我不了解对象内部的传播语法.
I don't understand about spread syntax inside objects.
console.log(...false) // TypeError not iterable
console.log(...1) // TypeError not iterable
console.log(...null) // TypeError not iterable
console.log(...undefined) // TypeError not iterable
我了解上述代码由于没有迭代器而发生错误.
I understand above codes that occurs error because of none-iterator.
但是这些代码运行良好.
But these codes are working well.
console.log({...false}) // {}
console.log({...1}) // {}
console.log({...null}) // {}
console.log({...undefined}) // {}
请让我知道上面的代码为什么起作用.
Please let me know why the above codes are working.
推荐答案
对象传播是完全不同的.它映射到 Object.assign()
The object spread is quite different. It maps to Object.assign()
internally.
因此, const a = {... 1}
与 const a = Object.assign({},1)
在这里, Object.assign({},1)
将 1
视为 object
,而不是 number
.因此,您没有抛出任何异常.
So const a = {...1}
is same as const a = Object.assign({}, 1)
Here Object.assign({},1)
has treated 1
as object
not as number
. Therefore, you did not get any exception thrown.
另外,如果您对数组 [... 1]
尝试了相同的操作,则应该抛出错误,因为它不会将 1
视为 object
,您将获得与 .. 1
.
Additionally if you have tried same thing for arrays [...1]
it should have thrown error, since it does not treats 1
as object
and you get the same behavior as ..1
.
总结:
console.log({...false}) => console.log(Object.assign({}, false))
console.log({...1}) => console.log(Object.assign({}, 1))
console.log({...null}) => console.log(Object.assign({}, null))
console.log({...undefined}) => console.log(Object.assign({}, undefined))
这篇关于我不了解对象内部的传播语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!