gpt4 book ai didi

javascript - 如何使用javascript从数组中删除元素

转载 作者:行者123 更新时间:2023-12-02 14:07:19 25 4
gpt4 key购买 nike

我有 2 个数组,想要根据第一个数组上的位置编号删除第二个数组的元素。

var notexists = []; //value is "1","5","8" on 0,1,2nd position. 
var copyrequiredfields = [];//Value is "a","b","c","d","e","f",...
for (var i = 0; i < notexists.length; i++) {
copyrequiredfields.splice(parseInt(notexists[i]), 1);
}

按照示例,我想从 copyrequiredfields 中删除第 1 个、第 5 个和第 8 个元素。请提出一些答案。

最佳答案

创建一个新数组,迭代copyrequiredfields,当note中的索引存在时,忽略它。

示例:

var notexist = [1,2,5];
var copyrequiredfields = ['a','b','c','d','e','f','g'];
//create a index map
var index_map = {};
for(var i = 0; i < notexist.length; i++){
index_map[notexist[i]] = true;
}
//remove the elements
var newarray = [];
for(var i = 0; i < copyrequiredfields.length; i++){
if(!index_map[i]){
newarray.push(copyrequiredfields[i]);
}
}
copyrequiredfields = newarray;

关于javascript - 如何使用javascript从数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39929043/

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