javascript方法array.shift()返回undefined

时间:2017-12-26 10:26:08

标签: javascript arrays

我有这段代码,根据布尔变量从数组中删除第一个(或最后一个)元素。我喜欢这个:

{...
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的全局变量。 这是为什么?

3 个答案:

答案 0 :(得分:2)

更改功能如下:



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)




答案 1 :(得分:0)

这对我来说非常好;

var deleteWaypoint = function (waypoints) {
  if (this.first) {
    this.first = false;
    waypoints.shift()
  } else {
    this.first = true;
    waypoints.pop()
  }
};

this.first = true
var waypoints = [1,2,3,4,5];
console.log("length before " + waypoints.length);
deleteWaypoint(waypoints)
console.log("length after " + waypoints.length);

Array.shift()返回已删除的数组,位于从问题中发布的代码中复制的下一行

waypoints = this.deleteWaypoint(waypoints)

数组的引用被重新分配给已删除的元素,该元素不是数组,并且没有length属性,因此返回undefined

答案 2 :(得分:0)

是的,它是正确的,因为返回return waypoints.shift()将返回从数组中删除的单个元素。你可以这样做 第一, waypoints.shift() 然后, return waypoints