如何从JavaScript数组中删除元素?
我想删除数组中的值,但下面的代码不起作用:如何从JavaScript数组中删除元素?,javascript,Javascript,我想删除数组中的值,但下面的代码不起作用: stations=['stations1','stations2'] wayPoints=[{location: "stations1"},{location: "stations2"},{location: "stations3"},{location: "stations4"}] deletStations(){ let result=[]; this.stations.forEach(index1 => rest.push(this.
stations=['stations1','stations2']
wayPoints=[{location: "stations1"},{location: "stations2"},{location: "stations3"},{location: "stations4"}]
deletStations(){
let result=[];
this.stations.forEach(index1 => rest.push(this.arrayRemove(this.wayPoints,index1)) );
}
arrayRemove(arr, value) {
return arr.filter(function(ele){
return ele != value;
});
}
上述代码不会从航路点删除
{location:“stations1”}、{location:“stations2”}
,请给出建议?以下是一种方法:
const secondWayOfDoingIt = wayPoints.filter(
element => !stations.includes(element.location)
);
与此相同,但使用了解构参数:
const firstWayOfDoingIt = wayPoints.filter(
({ location }) => !stations.includes(location)
);
希望有帮助。
Array.prototype.filter
不会改变输入数组,而是返回一个新数组。除非您手动设置值,否则它不会覆盖航路点
。这是否回答了您的问题@Wendelin我试过了,但没用Nbokmans有办法覆盖吗waypoints@Javauser手动将arrayRemove
调用的结果分配给航路点
。