[英]hello filter() javascript problem clic metods
Hello everyone who knows the filter()
method how I can tell if 2 or 3 values are the same in an array of n removes only one with each click ex an array [1,2,3,1, 3,4,5,3,1,1,4]
because with filter it will remove me every 1
or every 4
I would in fact like it to remove a 1 or a 4 for each click.大家好,知道filter()
方法的人如何判断 n 数组中的 2 或 3 个值是否相同,每次单击都会删除一个数组[1,2,3,1, 3,4,5,3,1,1,4]
因为使用过滤器,它会每1
或每4
删除我一次,我实际上希望它为每次点击删除 1 或 4。
var butonAll = document.querySelectorAll("#supprimer");
console.log(butonAll);
butonAll[i].addEventListener("click", function (e) {
console.log("supprime moi");
const id = e.target.getAttribute("data-id");
objectJs2 = objectJs2.filter(function (obj, i) {
console.log(obj, i);
if (obj != id) return true;
});
objectJs = objectJs.filter(function (obj, i) {
console.log(obj[0]._id, i);
if (obj[0]._id != id) return true;
});
localStorage.setItem("object", JSON.stringify(objectJs));
localStorage.setItem("id", JSON.stringify(objectJs2));
console.log(id);
console.log(objectJs.length);
console.log(line2);
location.href = "panier.html";
if (objectJs.length === 0) {
localStorage.clear();
}
});
Array#filter will takes a function as a parameter that is executed against every elements of the array, independently. Array#filter将一个函数作为参数,独立地针对数组的每个元素执行。
If you want to only filter the first matching element, you could use an external variable to keep track of it:如果只想过滤第一个匹配元素,可以使用外部变量来跟踪它:
let matched = false
let filtered = array.filter(x => {
if (matched) return true
if (x.id == id) {
matched = true
return false
}
return true
})
An alternative approach would be to find the index to remove using either indexOf
or findIndex
and to remove it with splice
另一种方法是使用indexOf
或findIndex
找到要删除的索引,并使用splice
删除它
let index = array.indexOf(id);
array.splice(index, 1);
Maybe you want this.也许你想要这个。
var arr = [1, 2, 3, 1, 3, 4, 5, 3, 1, 1, 4] console.log(arr); //Remove the first number one let has = arr.indexOf(1) //splice can remove data if receive negative numbers if (has > -1) arr.splice(has, 1) console.log(arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.