使用atom的JavaScript,在使用es6类时给出错误

时间:2018-10-02 17:21:38

标签: javascript processing p5.js es6-class

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

因此,我试图与编码训练神经网络系列一起使用,在原子序列上使用p5.js,在该系列的第10章中,当我遵循该方法时,编码训练将Matrix代数代码更新为es6。收到上面列出的错误,因为该代码在教程视频中显示为可以正常工作,所以我认为错误是在切换到es6语法之前,如何iv设置atom,btw,代码仅使用函数而不是类运行良好。 iv尝试将语法转换为babel,但这没有区别。还有其他人尝试过本教程吗?您如何设置一切才能使其正常工作?感谢您的帮助。

(如果有人问iv Triple,请检查是否已从教程中正确复制了它)

这是所有代码。

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);
}}}}}

编辑:这只是一个愚蠢的错误,现在已解决,感谢您的答复。

2 个答案:

答案 0 :(得分:0)

您的错误是将函数放入构造函数中。您必须在构造函数外部但在类内部声明它,如下所示 也像上面的注释中提到的那样,构造函数应该小写:

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);
      }
    }
  }

}

是的,您不需要在类内部使用“功能”。签出https://javascript.info/class

答案 1 :(得分:0)

如果您更好地格式化代码(例如,使用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);
      }
    }
  }
}
相关问题