js中数组删除某些元素,我们可以通过 filter 来处理。

const arr = [1, 2, 3, 4, 5];
// 使用 Array.filter() 删除数组中的元素 const newArr = arr.filter(item => item !== 3);// [1, 2, 4, 5]
// 使用 Array.map() 和 Array.filter() 删除数组中的元素 const newArr2 = arr.map((item, index) => item === 3 ? null : item).filter(item => item !== null); // [1, 2, 4, 5]

需要注意的是,Array.map() 本身并不会删除数组中的元素,而是返回一个新数组。因此,在使用 Array.map() 删除数组元素时,需要结合其他数组方法,如 Array.filter()

例如我们在Vue中,给数组 newTemplates 添加 isShow和explain 两个值,并将最后的数组删除其中key值为 discounts元素。

let _self = this
_self.newTemplates = _self.newTemplates.map((item, index) => {
	_self.$set(item, "isShow", item.display);
	_self.$set(item, "explain", _self.templates[item.key]);
	return item;
}).filter(item => item.key !== 'discounts');