获取'无效的返回语句'我也不知道为什么

Getting an 'invalid return statement' and I am not sure why

本文关键字:我也不知道 为什么 语句 无效 获取 返回      更新时间:2023-09-26

我正在编写Conway's Game of Life网格。

我是新的JavaScript,我正试图添加一个方法到板对象,将返回一个cell的位置在板上。但是我得到一个错误,告诉我这是一个invalid return statement。你能解释一下我做错了什么吗?

         Board.prototype = {
            addCell: function(cell) {
                this.cells[getCellRepresentation(cell.x, cell.y)] = cell;
            }
            getCellAt: function(x,y) {
                return this.cells[getCellRepresentation(x,y)]
            }
        }

我看到的第一件事是你少了一个逗号:

Board.prototype = {
        addCell: function(cell) {
            this.cells[getCellRepresentation(cell.x, cell.y)] = cell;
        },  // <---- put a comma here 
        getCellAt: function(x,y) {
            return this.cells[getCellRepresentation(x,y)]
        }
    }

您需要逗号的原因是这两个函数是初始化语句的一部分,并且addCell和getCellAt都是Board的成员。原型,并使用作为表达式列表成员的匿名函数表达式初始化。考虑JSON语法

var obj = {
 name: "bob",
 age: 21,
 party: function() { ... }
}

如果函数是普通的命名函数,您可能看到:

function addCell(cell) {
}
function getCellAt(x,y) {
}

不需要逗号,因为这些不是赋值语句,它们是单独的函数定义。

您缺少逗号。

Board.prototype = {
            addCell: function(cell) {
                this.cells[getCellRepresentation(cell.x, cell.y)] = cell;
            },
            getCellAt: function(x,y) {
                return this.cells[getCellRepresentation(x,y)]
            }
}