【问题标题】:javascript method array.shift() returning undefinedjavascript 方法 array.shift() 返回未定义
【发布时间】:2017-12-26 10:26:07
【问题描述】:

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

{...
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。 “First”是一个初始化为true的全局变量。 这是为什么?

【问题讨论】:

  • 一旦你的数组为空,你就会得到未定义,如here所述
  • Array.prototype.shift: shift() 方法从数组中删除第一个元素并返回删除的元素。”
  • 将您的退货声明更新为deleteWaypoint中的return waypoints
  • 也考虑给我们更多细节。你的阵列看起来如何? mcve
  • @Andreas 是的,现在在 waypoints.shift() 中修改;返回航点。谢谢。抱歉这个愚蠢的问题,如果你回答我会给你点赞和正确答案

标签: javascript arrays


【解决方案1】:

修改函数如下:

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)

【讨论】:

    【解决方案2】:

    这对我来说很好用;

    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)
    

    数组的引用被重新分配给已删除的元素,该元素不是数组且没有长度属性,因此返回未定义

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-10
        • 2017-12-14
        • 1970-01-01
        • 1970-01-01
        • 2020-10-05
        • 2015-01-02
        • 2019-03-27
        • 2023-04-11
        相关资源
        最近更新 更多