尝试以不可变的方式将数组插入现有数组,但不知何故我的代码无法正常工作。
function insertItem(array, action) {
return [
...array.slice(0, action.index),
action.item,
...array.slice(action.index)
]
}
const ori_arr = [{
id: 1,
name: 'james',
age: 10
}, {
id: 2,
name: 'terrance',
age: 20
}]
console.log(insertItem(ori_arr, {
action: {
index: 1,
item: {
id: 3,
name: 'she',
age: 44
}
}
}))
索引部分可能有误。
最佳答案
由于您要添加的对象具有嵌套属性 action
,您可能希望使用 destructuring
来获取 action
键您的 inserItem
函数的参数。
const insertItem = (array, { action }) => [
...array.slice(0, action.index),
action.item,
...array.slice(action.index),
];
const ori_arr = [{
id: 1,
name: 'james',
age: 10
}, {
id: 2,
name: 'terrance',
age: 20
}]
console.log(insertItem(ori_arr, {
action: {
index: 1,
item: {
id: 3,
name: 'she',
age: 44
}
}
}))
Hover,如果您希望避免解构
,只需更改 insertItem
函数中的第二个参数的名称,例如obj
然后在函数中的每个 action.index
之前添加 obj
:
const insertItem = (array, obj) => [
...array.slice(0, obj.action.index),
obj.action.item,
...array.slice(obj.action.index),
];
关于javascript - 无需推送即可将项目添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47282542/