添加元素(指定位置添加)
方法一:先复制前0~index个元素,将item元素插入之后,再拼接index之后的元素
function insert(arr
, item
, index
) {
let newArr
= arr
.slice(0, index
)
newArr
.push(item
)
newArr
= newArr
.concat(arr
.slice(index
))
return newArr
}
方法二:使用splice方法插入(效率较高)
function insert(arr
, item
, index
) {
let newArr
= arr
.slice(0)
newArr
.splice(index
,0, item
)
return newArr
}
方法三:push.apply+splice
function insert(arr
, item
, index
) {
let newArr
= [];
[].push
.apply(newArr
,arr
);
newArr
.splice(index
,0, item
);
return newArr
}
转载请注明原文地址:https://tech.qufami.com/read-2711.html