我正在尝试在JavaScript类构造函数中使用条件逻辑。
上下文:我在一个双for循环中创建了一个2d网格,每个单元格都有一个属性北、南、东和西。为了保持二维网格的边界,我试图只创建一个具有N,S,E属性的单元格,如果该单元格位于col0的边缘。
对于一个4x4的网格,我尝试构建这个项目,但是一直收到错误,"Uncaught : Unexpected '!='“。所以我认为问题出在我对Javascript语法的了解不足。有什么建议吗?
class Cell {
constructor(row,col){
this.visited = false;
this.row = row;
this.col = col;
this.edges = {
if(row!=0){
north:1,
},
if(row!=3)){
south:1,
},
if(col!=0)){
west:1,
},
if(col!=3)){
east:1,
},
}
}
}发布于 2020-02-13 05:10:26
我会使用三元运算符,而不是if语句。关于Conditional (ternary) operator,请阅读以下内容:
条件(三元)运算符是唯一接受三个操作数的JavaScript运算符:条件后跟问号(?),然后是条件为真时要执行的表达式,后跟冒号(:),最后是条件为假时要执行的表达式。此运算符经常用作if语句的快捷方式。
例如,这是一个适合您的情况的语法:
const row = 2;
const col = 3;
const edges = {
north: row != 0 ? 1 : 0,
south: row != 3 ? 1 : 0,
west: col != 0 ? 1 : 0,
east: col != 3 ? 1 : 0
};
console.log(edges);
我希望这对你有帮助!
发布于 2020-02-13 05:10:40
您可以使用ternary operator
class Cell {
constructor(row, col) {
this.visited = false;
this.row = row;
this.col = col;
this.edges = {
north: row !== 0 ? 1 : null,
south: row !== 3 ? 1 : null,
west: col !== 0 ? 1 : null,
east: col !== 3 ? 1 : null
};
}
}发布于 2020-02-13 05:10:55
不能在对象文字内使用if语句。相反,您应该使用if语句直接分配给对象的字段:
this.edges = {};
if (row != 0) {
this.edges.north = 1;
}
// etc.https://stackoverflow.com/questions/60196850
复制相似问题