我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
我这样做:
const insert = (what, where, index) =>
([...where.slice(0, index), what , ...where.slice(index, where.length)]);
常量插入=(what,where,index)=>([…where.slice(0,index),what,…where.slice(index,where.length)]);常量列表=[1,2,3,4,5,6];const newList=插入('a',列表,2);console.log(newList.indexOf('a')==2);
其他回答
我这样做:
const insert = (what, where, index) =>
([...where.slice(0, index), what , ...where.slice(index, where.length)]);
常量插入=(what,where,index)=>([…where.slice(0,index),what,…where.slice(index,where.length)]);常量列表=[1,2,3,4,5,6];const newList=插入('a',列表,2);console.log(newList.indexOf('a')==2);
您需要在本机阵列对象上使用拼接函数。
arr.splice(索引,0,项);将在指定的索引处向arr中插入项目(首先删除0个项目,也就是说,这只是一个插入)。
在本例中,我们将创建一个数组,并将一个元素添加到索引2中:
var arr=[];arr[0]=“Jani”;arr[1]=“Hege”;arr[2]=“过时”;arr[3]=“Kai Jim”;arr[4]=“博格”;console.log(arr.jjoin());//Jani、Hege、Stale、Kai Jim、Borgearr.splice(2,0,“Lene”);console.log(arr.jjoin());//Jani、Hege、Lene、Stale、Kai Jim、Borge
另一种可能的解决方案,使用Array.reduce。
const arr=[“苹果”、“橙色”、“覆盆子”];常量arr2=[1,2,4];常量插入=(arr,项,索引)=>arr.reduce(函数,a,i){i==索引?s.push(项目,a):s.push(a);返回s;}, []);console.log(插入(arr,“香蕉”,1));控制台日志(插入(arr2,3,2))
任何对这个问题仍有疑问的人,都尝试过前面答案中的所有选项,但都没有得到。我分享我的解决方案,这是为了考虑到您不想显式地声明对象与数组的财产。
function isIdentical(left, right){
return JSON.stringify(left) === JSON.stringify(right);
}
function contains(array, obj){
let count = 0;
array.map((cur) => {
if(this.isIdentical(cur, obj))
count++;
});
return count > 0;
}
这是对引用数组进行迭代并将其与要检查的对象进行比较的组合,将两者转换为字符串,然后在匹配时进行迭代。然后你就可以数了。这是可以改进的,但这是我解决的问题。
下面是一个支持同时插入多个值的简单函数:
function add_items_to_array_at_position(array, index, new_items)
{
return [...array.slice(0, index), ...new_items, ...array.slice(index)];
}
用法示例:
let old_array = [1,2,5];
let new_array = add_items_to_array_at_position(old_array, 2, [3,4]);
console.log(new_array);
//Output: [1,2,3,4,5]