[英]“TypeError: Invalid attempt to spread non-iterable instance”: Adding either an Array or Object to an Array
So, to add one array to another in Javascript there is:因此,要在 Javascript 中将一个数组添加到另一个数组,有:
concat()连接()
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = x.concat(y);
// x = ['a', 'b', 'c'] (remains unchanged)
// y = ['d', 'e', 'f'] (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']
push.apply() push.apply()
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
x.push.apply(x, y);
// x = ['a', 'b', 'c', 'd', 'e', 'f']
// y = ['d', 'e', 'f'] (remains unchanged)
...spreadOperator ...传播运算符
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = [...x, ...y];
// x = ['a', 'b', 'c'] (remains unchanged)
// y = ['d', 'e', 'f'] (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']
However, let's say that var x
is an Array
of Objects
, and var y
could either be an Array
of more Objects
or an Object
instance...但是,假设var x
是一个Objects
Array
,而var y
可以是一个包含更多Objects
的Array
,也可以是一个Object
实例...
Q.) I was wondering if there is a quick method that can handle the creation of a new Array
from either two Arrays or one Array and a singular object...?问。)我想知道是否有一种快速方法可以处理从两个 Arrays 或一个 Array 和一个单一 object... 创建新Array
? I assumed the following might work:我假设以下可能有效:
let x = []
let y = {} OR []
let z = [...x, ...y];
When y
is an Array
, this is fine, but when y is an Object
we would see the TypeError: Invalid attempt to spread non-iterable instance
...so, are there any possible methods to avoid such a scenario?当y
是Array
时,这很好,但是当 y 是Object
时,我们会看到TypeError: Invalid attempt to spread non-iterable instance
...那么,有没有可能的方法来避免这种情况?
As Harmandeep said, this could be an implementation:正如 Harmandeep 所说,这可能是一个实现:
const concat = (a,b) => [...a, ...(Array.isArray(b)? b: [b]) ] console.log( concat([{a:'a'}], [{b:'b'}]), concat([{a:'a'}], {b:'b'}), )
let x = ['a', 'b'] let a = {} let b = [{}] console.log(x.concat(a)) console.log(x.concat(b))
It depends on what you are trying to achieve.这取决于您要达到的目标。
let x = ['a','b']
let y = {} OR [{}]
let z = ...;
If you are expecting如果你期待
z = ['a','b',{}]
Array.prototype.concat can solve this. Array.prototype.concat 可以解决这个问题。
let z = x.concat(y)
Array.prototype.concat handles arrays and non arrays and append them accordingly Array.prototype.concat相应地处理 arrays 和非 arrays 和 append 它们
are there any possible methods to avoid such a scenario?有没有可能的方法来避免这种情况?
Yes, type guards是的, 类型保护
let y: object | Array<object> = {}
let z: Array<any> = [];
if(y instanceof Array) {
let z = [...x, ...y];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.