首页 > 解决方案 > 试图过滤数组

问题描述

我有这个代码:

console.log(this.productlist[this.productlist.length-1] === product); //says: true
this.productlist == this.productlist.filter(p => p !== product);
console.log(this.productlist);  //the product is still in the list

我想productthis.productlist. 第一个 console.log 说的是真的,所以两个对象是一样的。但是第二个 console.log 显示该产品仍在列表中。

我在其他地方使用过滤器,它在那里工作。我一无所知。我该怎么做才能找出为什么这在这里不起作用?

标签: javascript

解决方案


从数组中删除最后一项的各种方法:

使用过滤器:

array = array.filter((elem,index) => index != array.length-1)

使用拼接:

array.splice(array.length-1)

使用切片:

array.slice(0,array.length-1)


推荐阅读