gpt4 book ai didi

javascript从特定索引的列表中添加和删除多个值

转载 作者:搜寻专家 更新时间:2023-11-01 04:14:28 27 4
gpt4 key购买 nike

我有这样的代码:

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [1, 3] // ball and dog
var to = 5 // fish

for(var i in index){
console.log(index[i])
var local_data = data
data.splice(to, 0, data.splice(index[i]), 1)
}

console.log(data)
console.log(index)

JsFiddle

这里的var index = [1,3]就是要设置的数据的索引值。

我在这里想要的是,设置index i 的值。 e balldogfish 之后,其余的留在订单上。

插入后,我希望根据 balldog i 的新位置更改 index 值。 e [4, 5]

更新数据

最后我想要这样的结果:console.log(data) 应该给

["apple", "cat", "elephant", "fish", "ball", "dog", "gorilla"]

console.log(index)应该给出:

[4, 5] // new value of ball and dog

最佳答案

你可以这样做。

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [4, 5];
var to = 2 ;

var arrTemp = [];

data.forEach(function(val,key){

if(index.indexOf(key)!=-1){

data.splice((to+1),0,data[key]);
to++;
delete data[key];

}
})
data = data.filter(function(val){ return val != undefined });

console.log(data)


UPDATE :

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [ 2,3];
var to = 5 ;
var arrTemp = [];

data.forEach(function(val,key){

if(index.indexOf(key)!=-1){
arrTemp.push(data[key]);
delete data[key];

}
})

to=to+1;
for(var pos=0;pos<index.length;pos++){
data.splice(to++,0,arrTemp[pos])
}
data = data.filter(function(val){ return val != undefined });

JsFiddle

关于javascript从特定索引的列表中添加和删除多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37936397/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com