简体   繁体   English

可以使用数组中的扩展运算符和 JavaScript 中的 object 找出差异

[英]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.

相关问题 在循环中使用扩展运算符与 javascript 中的 object 文字 - Using spread operator in a loop with object literals in javascript 使用扩展运算符将对象添加到数组的开头 - Add object to the beginning of array using spread operator 使用传播运算符将对象推入数组吗? - Push an object into the array using spread operator? 在使用扩展运算符修改 object 属性时,如何保留数组中 object 的索引? - How can the index of an object within an array be preserved when modifying an object property while using the spread operator? Javascript 多级 object 扩展运算符 - Javascript multilevel object spread operator 如何在javascript中使用扩展运算符更新内部对象数组 - How to in javascript update inner object array with spread operator 如何使用扩展运算符使用扩展运算符使用反应从对象数组中删除 object? - How to use spread operator to delete an object from array of objects using spread operator using react? 使用spread运算符更新数组对象对象值 - Update array object object value using spread operator 如何在不使用扩展运算符的情况下扩展数组? - How to spread an array without using a spread operator? Javascript 展开运算符可以包含对象的未定义字段吗? - Can Javascript spread operator include undefined fields of an object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM