JS - 拆分数组字符串并将两个部分作为参数传递给方法

时间:2017-02-18 11:21:53

标签: javascript arrays string split

所以,我有一种从x,y坐标中获取特定DIV的方法:

this.getCell = function (x, y){
      this.index = x + y * this.width;
      return this.cells[this.index];
}

我想用另一个方法使用我的方法:

this.computeCellNextState = function(x, y){

      var nearbies = ['x-1,y-1','x,y-1','x+1,y-1'];
      var splitter = nearbies[0].split(',');

      console.log(this.getCell(splitter[0],splitter[1])); // returns undefined

}

我想要实现的目标:

this.getCell(x-1,y-1)

x-1,y-1 are from nearbies[0]

我想拆分一串“近亲”'并用作2个参数。

1 个答案:

答案 0 :(得分:1)

'x-1,y-1'等只是字符串,它们对getCell没有任何意义。您必须使用computeNextState中的实际表达式,例如

this.computeCellNextState = function(x, y){

      var nearbies = [[x-1,y-1],[x,y-1],[x+1,y-1]];

      console.log(this.getCell(...nearbies[0]))

}