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

2024-02-16

const data = response.data
console.log(data)
const temp = data.ssps_with_scated.splice(5, 1)(1, 3)[0]
data.ps_with_ed.splice(2, 1, 0, temp) 

我正在努力实现最终我得到了它。但问题是,我不能期望数组值始终相同。所以我决定根据 ID 重新排列数组值。


Well,

splice(7,1)(21,3)

这段代码会导致错误。由于 Array.prototpy.slice 返回一个新数组。
如果你这样做的话,结果是一样的:

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

编辑: 也许有更快/更好的解决方案,但是...... 您可以使其更通用,但仅适用于您的情况:

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐