【问题标题】:JavaScript Array undefined element [duplicate]JavaScript Array未定义元素[重复]
【发布时间】:2017-04-25 02:48:43
【问题描述】:

我有一个函数应该在数组的开头添加一个元素。 但我总是在我的数组末尾得到一个未定义的元素。我希望有人可以帮助我:)

function putToFirst(e){
   var array = [];
   array.push(e);
   this.arrayList = array.concat(this.arrayList);
}

编辑:

class List {

  constructor () {
    super()
    this.arrayList = [];
  }

  putToFirst(e) {
      this.ArrayList.unshift(e);
 }
}

这就是类。我从类列表中创建一个新对象,并在该对象上调用函数 putToFirst。但我最后总是得到一个“未定义”的数组

【问题讨论】:

  • [].unshift() 在您的浏览器中损坏了吗?!
  • e 是什么? this 是什么?尝试提供minimal reproducible example
  • 请注意,如果您在 this.arrayList 上使用 unshift,您将改变数组而不是用新数组替换它。
  • e 是一个整数,应该添加到数组中。这是调用函数的对象
  • @Alex9677 — 那个对象是什么?你如何测试结果?提供minimal reproducible example

标签: javascript arrays undefined


【解决方案1】:
this.arraylist is wrong this represent a current object you are not currently using any class in above code you just need to change 

  function putToFirst(e){
   var array = [];
   var arrayList=[];
   array.push(e);
  arrayList = array.concat(arrayList);
  console.log(arrayList);
}

【讨论】:

  • 我不会认为this.arrayList 是错误的。但是,您的函数每次都会创建一个新的空 arrayList。这与将新元素附加到数组的开头无关。
  • 感谢您指出我的错误
猜你喜欢
  • 1970-01-01
  • 2018-06-10
  • 2020-07-14
  • 1970-01-01
  • 2017-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-26
相关资源
最近更新 更多