[英]Can figure out the difference using spread operator in array and object in JavaScript
I am using spread operator in an array like below:我在如下数组中使用扩展运算符:
const addOne = false; const arr = [1, 2, 3] const arr1 = [...arr, ...(addOne && [8, 9])]; console.log(arr1)
And I got the error我得到了错误
TypeError: (addOne && [8,9]) is not iterable
at <anonymous>:4:32
While if I use spread operator in an object like:而如果我在 object 中使用扩展运算符,例如:
const addOne = false; const obj = { name: 'peter', age: 23 } const obj1 = {...obj, ...(addOne && obj) } console.log(obj1)
it prints out the correct output它打印出正确的 output
Anyone knows why?有谁知道为什么?
(false && obj)
evaluates to a boolean so its' not iterable. (false && obj)
的计算结果为 boolean,因此它不可迭代。
When using the spread operator when building your obj1
object, js uses a different method to extract the key value pairs from an object (remember that a bool value in js is still an object), so it won't throw an error since it's expecting an object as an input.在构建
obj1
object 时使用扩展运算符时,js 使用不同的方法从 object 中提取键值对(请记住,js 中的 bool 值仍然是一个对象),因此它不会抛出错误,因为它期待object 作为输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.