【问题标题】:Method .includes() is not a function error方法 .includes() 不是函数错误
【发布时间】:2019-04-13 23:45:59
【问题描述】:

我正在学习 Eloquent Javascript,我有以下代码作为练习之一。

class Group {
constructor(){
    this.arr = []
}

add(value){
    if(!this.has(value)) {
        this.arr = this.arr.push(value)
    }
}

has(value){
    return this.arr.includes(value);
}

delete(value){
    this.arr = this.arr.filter(n => n !== value)
}

static from(collection){
    let rec = new Group;
    for (let value of collection){
        rec.add(value)
        }
return rec
    }
}

这似乎是正确的,它应该可以工作,但我得到了错误

TypeError: arr.includes 不是函数

那是关于什么的?我找不到答案。

【问题讨论】:

标签: javascript function methods include typeerror


【解决方案1】:

来自docs

push() 方法将一个或多个元素添加到数组的末尾,并且 返回数组的新长度。

因此,问题在于这条线。 this.arr 在这一行之后不再是一个数组。

this.arr = this.arr.push(value)

因此,将其更新为以下

this.arr.push(value)

【讨论】:

  • 谢谢,arr变量当然变成了数字!!
  • @Zhast - 很高兴为您提供帮助!
猜你喜欢
  • 1970-01-01
  • 2017-06-08
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
  • 2020-01-13
相关资源
最近更新 更多