我需要从数组中删除一个元素并返回剩余的元素。
我尝试使用 splice
和 filter
但无法使其正常工作。
使用 splice
只会返回已删除的元素,但是我需要相反的结果。
var parse_obj = JSON.parse(document.getElementById('imagens').value);
function rImagem(data){
data = data - 1;
document.getElementsByClassName("btn_remover")[data].style.display = 'none';
parse_obj2 = parse_obj.splice(parse_obj.findIndex(e => e.data,1));
new_string = JSON.stringify(parse_obj2);
document.getElementById('imagens').value = new_string;
}
parse_obj
?.splice()
会直接在原数组上进行修改,所以一旦你运行了parse_obj.splice
,它就会是已经移除了该项的数组。 - VLAZsplice()
method returns the deleted element from the array. You are trying to assign this deleted element in the arrayparse_obj2
. What you should do is not assign anything to the variableparse_obj2
and use theparse_obj
array as it is.parse_obj.splice(parse_obj.findIndex(e => e.data,1));
new_string = JSON.stringify(parse_obj2);
- Srishti Gupta