简体   繁体   English

如何拼接多个数组元素并相应插入?

[英]How to splice multiple array elements and insert accordingly?

 groupsCall(callType, params) { let url = `/api/v3/campaigns/${this.campaignId}/`, errorMessage = `could not load the filters` url = callType === 'get' ? url + 'selected_groups' : url + 'update_groups' axiosConfig[callType](url, params) .then((response) => { const data = response.data console.log(data) const temp = data.groups_with_selected.splice(7,1)(21,3)[0] data.groups_with_selected.splice(2,21,0,temp) if (isObject(data)) { this.setGroupsData(data) this.getTotalCount() errorMessage = '' this.setUpdating(data) } this.errorMessage = errorMessage }) .catch((error) => { errorMessage = `${errorMessage}. ${error}` this.errorMessage = errorMessage this.updating = false }) },

How to splice multiple array elements and insert accordingly?如何拼接多个数组元素并相应插入?

In the above code, from the response.在上面的代码中,来自响应。 I am splicing the array element position and placing them in certain position.我正在拼接数组元素位置并将它们放在某个位置。

i want to splice the (7th position to 2nd position) and (21st position to 3rd position)我想拼接(第7位到第2位)和(第21位到第3位)

But during that process, I couldn't able to re-arrange the order.但在这个过程中,我无法重新安排订单。

Well,好,

splice(7,1)(21,3)

This code will cause an error.此代码将导致错误。 Since Array.prototpy.slice returns a new array.由于 Array.prototpy.slice 返回一个新数组。
It would be the same if you would do this:如果你这样做也是一样的:

const a = [1,2,3]
const b = a.splice(1,1);
b(2,1) // b.splice(...) is not a function

EDITED: Maybe there is a faster/better solution but... You can make it more general but for your case only:编辑:也许有一个更快/更好的解决方案,但是......你可以让它更通用,但只针对你的情况:

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
const first = array[7];
const second = array[21];

// Add elements on certain indices in array (second and third)
array.splice(2, 0, first, second)

// Remove first from the array (index is 7 + 2 because we added 2 elements)
array.splice(9, 1)

// Remove 21 from the array (index is 22 - 1 because we added 2 elements and removed 1, not: number 21 is on index 22)
array.splice(21, 1);

data shouldn't be a const since the value is getting updated. data不应该是const因为值正在更新。 Splice can also only be called on one array at a time.一次只能在一个数组上调用Splice If you need to call it on multiple arrays, create a loop or iterate over them.如果您需要在多个数组上调用它,请创建一个循环或迭代它们。

If you want to inject the current value of the 7th position into the 2nd position... you'd need to do something like...如果你想将第 7 个位置的当前值注入到第 2 个位置......你需要做一些类似的事情......

array.splice(2, 0, array[7])

One way :单程 :

 arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21] arr.splice(2, 0, arr[7], arr[21]) arr.splice(9, 1) arr.splice(22, 1) console.log(JSON.stringify(arr)) //[0,1,7,21,2,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20,]

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

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