我有一段代码,根据布尔变量,从数组中删除了第一个(或最后一个)元素。我喜欢这样:
{...
console.log("length before " + waypoints.length)
waypoints = this.deleteWaypoint(waypoints)
console.log("length after " + waypoints.length)
...}
deleteWaypoint(waypoints){
if (this.first){
this.first = false;
return waypoints.shift()
} else {
this.first = true;
return waypoints.pop()
}
}
第一个日志打印的
waypoints
具有一定的长度,然后我调用删除元素的方法,第二个日志打印的是length after undefined
。 “第一”是初始化为true的全局变量。这是为什么?
最佳答案
更改功能如下:
var waypoints = [1,2,3,4,5,6,7,8,9,0];
var deleteWaypoint = (waypoints)=>{
if (this.first){
this.first = false;
waypoints.shift();
return waypoints
} else {
this.first = true;
waypoints.pop()
return waypoints
}
}
console.log("length before " + waypoints.length)
waypoints = deleteWaypoint(waypoints)
console.log("length after " + waypoints.length)