JavaScript 使用 atom ,使用 es6 时出错 类

JavaScript using atom , gives error when using es6 classes

a link to the tutorial, this is the error i get

所以我试图跟随编码训练神经网络系列,在原子上使用 p5.js,在该系列的第 10 集中,编码训练将矩阵代数代码更新为 es6,当我跟随随着这个我得到上面列出的错误,因为代码显示在教程视频中工作我假设错误在于 iv 如何设置原子,顺便说一句,在切换到 es6 语法之前,代码 运行 很好,只是使用函数不是 类。我尝试切换到 babel 作为所使用的语法,但这没有区别。有没有其他人尝试过遵循本教程?您是如何设置一切以使其正常工作的?感谢您的帮助。

(如果有人问 iv 三重检查它是否从教程中正确复制)

这是所有代码。

class Matrix{
Constructor(rows,cols){

this.rows=rows;
this.cols=cols;
this.matrix=[];

for(let i =0;i<this.rows;i++){
this.matrix[i]=[];
for(let j=0;j<this.cols;j++){
this.matrix[i][j]=0;
}
}

randomize(){
for(let i =0;i<this.rows;i++){
for(let j=0;j<this.cols;j++){
this.matrix[i][j]+=Math.floor(Math.random()*10);
}}}}}

编辑:只是一个愚蠢的错误,现在解决了感谢回复。

你的错误是将函数放在构造函数中。您必须在构造函数外部但在 class 内部声明它,如下所示 也像上面评论中提到的构造函数应该是小写的:

class Matrix{

  constructor(rows,cols){
    this.rows=rows;
    this.cols=cols;
    this.matrix=[];

    for(let i =0;i<this.rows;i++){
      this.matrix[i]=[];
      for(let j=0;j<this.cols;j++){
        this.matrix[i][j]=0;
      }
    }
  }



  randomize(){
    for(let i =0;i<this.rows;i++){
      for(let j=0;j<this.cols;j++){
          this.matrix[i][j]+=Math.floor(Math.random()*10);
      }
    }
  }

}

是的,您不需要 class 中的 "function"。看看这个 https://javascript.info/class

如果您更好地格式化代码(例如使用 Prettier),错误会更明显。您放错了右花括号之一:构造函数中缺少一个,而代码末尾的花括号过多。

代码应如下所示:

class Matrix {
  constructor(rows, cols) {
    this.rows = rows;
    this.cols = cols;
    this.matrix = [];

    for (let i = 0; i < this.rows; i++) {
      this.matrix[i] = [];
      for (let j = 0; j < this.cols; j++) {
        this.matrix[i][j] = 0;
      }
    }
  }

  randomize() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.cols; j++) {
        this.matrix[i][j] += Math.floor(Math.random() * 10);
      }
    }
  }
}