简体   繁体   English

JavaScript Unshift 每个数组元素

[英]JavaScript Unshift EACH array element

I have two arrays that contain objects.我有两个包含对象的数组。 arr1 and arr2 . arr1arr2 If I unshift arr1 to contain the elements of arr2 , the elements are not appended individually into arr1 , instead the whole array ( arr2 ) is appended at the beginning, for example:如果我取消移动arr1以包含arr2的元素,则元素不会单独附加到arr1 ,而是将整个数组 ( arr2 ) 附加到开头,例如:

arr1 = [{ele:1}, {ele:2}]
arr2 = [{ele:3}, {ele:4}]

I get: arr1 = [[{ele:3}, {ele:4}], {ele:1}, {ele:2}]我得到: arr1 = [[{ele:3}, {ele:4}], {ele:1}, {ele:2}]

Notice the whole array inside instead of its objects.注意里面的整个数组而不是它的对象。

I want: arr1 = [{ele:3}, {ele:4}, {ele:1}, {ele:2}]我想要: arr1 = [{ele:3}, {ele:4}, {ele:1}, {ele:2}]

My arrays are ko.observableArray(), maybe that makes a difference?我的数组是 ko.observableArray(),也许这有区别?

你去吧:

[].unshift.apply(arr1, arr2);

maybe this might be bit simpler也许这可能更简单一些

let arr1 = [{ ele: 1 }, { ele: 2 }];
let arr2 = [{ ele: 3 }, { ele: 4 }];
for (const iterator of arr2) {
  arr1.unshift(iterator);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM