我在jQuery中有以下关联数组:
var main_new_smarket_image_tags_list = {
1: "value1",
4: "value4",
2: "value2",
8: "value8"
};
我想根据索引的值删除元素。例如,删除索引为2
的元素。然后它看起来像这样:
main_new_smarket_image_tags_list = {
1: "value1",
4: "value4",
8: "value8"
};
答案 0 :(得分:1)
我正在修改我的答案,因为我对你的问题和实际代码感到困惑。你的问题涉及数组,但你的代码是一个对象。
由于您正在使用对象,因此需要获取要删除的值的键,然后调用delete object[key]
。
实施例
var main_new_smarket_image_tags_list = {
1: "value1",
4: "value4",
2: "value2",
8: "value8"
};
var key = 2;
delete main_new_smarket_image_tags_list[key];
//{"1": "value1", "4": "value4", "8": "value8"}
console.log(main_new_smarket_image_tags_list);

答案 1 :(得分:0)
以下是解决方案:https://codepen.io/creativedev/pen/eKGXVr
var main_new_smarket_image_tags_list = {
1: "value1",
4: "value4",
2: "value2",
8: "value8"
};
var removeindex = 2;
var newcontent = {};
$.each(main_new_smarket_image_tags_list, function(i,v){
if(i != removeindex){
newcontent[i] = v;
}
})
console.log(newcontent);
答案 2 :(得分:0)
答案 3 :(得分:-1)
您可以遍历整个对象并delete
值匹配的键:
var main_new_smarket_image_tags_list = {
1: "value1",
4: "value4",
2: "value2",
8: "value8"
};
var value_to_delete = "value2"; // <-- could come from anywhere.
for (var key in main_new_smarket_image_tags_list) { // <-- loops over all items
if (main_new_smarket_image_tags_list[key] === value_to_delete) { // <- checks for the value
delete main_new_smarket_image_tags_list[key]; // <-- this deletes they key (along with the value)
}
}