javascript - 方法 .includes() 不是函数错误

标签 javascript function methods include typeerror

我正在通过 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 is not a function

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

最佳答案

来自docs ,

The push() method adds one or more elements to the end of an array and returns the new length of the array.

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

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

因此,将其更新为以下内容

this.arr.push(value)

关于javascript - 方法 .includes() 不是函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242108/

相关文章:

Objective-c 看不到 Swift 类的方法

javascript - json 对象拆分为两个 json 对象

python - 如何使用 Pygame 矩形

java - Java是“按引用传递”还是“按值传递”?

javascript - 如何将选择下拉选项的值与 div 类进行比较以切换它的可见性?

c++ - Xcode 在函数中使用时如何使用 IBOutlet 进行标记

java - 如何从 Oracle Forms 6i 调用 Java 对象/函数?

javascript - FlowJS : How to use union types and boolean literals

javascript - 使用 Object.create(null) 与 {} 相比是一种不好的做法吗?

javascript - 如何在滚动(和窗口调整大小)上将 div 定位为 'sticky'?