[英]Trying to learn For loops the right way
我最近一直在教我自己的Node.JS,它很有趣。 但是,我遇到了一个路障,确实在这里杀死了我。 我已经意识到我无法绕过JS中的For循环。 每当我用于循环时,我最终只会使用jquery $ .each()来省掉我的头。 好吧,我不能依靠.each来实现自己的目标,而我被困在试图将头缠绕在For循环上。 这是我正在使用的。
仅在某些情况下,我一直在使用node.js中的websocket。 其乐无穷! 我从随处可见的标准ChatApp开始,现在我正在尝试构建多人井字游戏。 当玩家单击网格时,网格选项将存储在node.js Websocket服务器上玩家对象内部的列表中。
我要做的最后一件事是将选取的板节点列表与可能的井字解决方案的主列表进行比较:
//i'm sure this can be formatted better....
var solutions = {
'vert':{
1:[[0,0],[0,1],[0,2]],
2:[[1,0],[1,1],[2,1]],
3:[[2,0],[2,1],[2,2]]
},
'hor':{
1:[[0,0],[1,0],[2,0]],
2:[[0,1],[1,1],[2,1]],
3:[[0,2],[1,2],[2,2]]
},
'diag':{
1:[[0,0],[1,1],[2,2]],
2:[[2,0],[1,1],[0,2]]
}
};
// player selected grid coordinates
var player1 = {
'picked':[[0,0],[1,1],[2,2]]
};
// the big dumb function that I hate.
function winCondition(solutions){
var win = '';
console.log('-------------------------------------------------------');
if(win === ''){
$.each(solutions, function(index, solution){
$.each(solution, function(index, winCon){
console.log('testing Win Condition ' + index,winCon);
matches = 0;
if(matches !== 3){
console.log('current match value = ' + matches);
$.each(winCon, function(index, gridSlot){
console.log('Testing ' + index,gridSlot);
$.each(player1.picked, function(index,gridChoice){
console.log('does '+ gridSlot + ' = ' + gridChoice);
if(gridSlot[0] == gridChoice[0] && gridSlot[1] == gridChoice[1]){
matches = matches + 1;
console.log('match! ' + matches + '/3 left');
if(matches == 3){
win = true;
}
}
});
});
}
});
});
}
if (win === true){
return true;
} else {
return false;
}
}
我在codepen中测试了一段时间,除了缺少.each服务器端外,它似乎可以按我的要求工作!
因此,如何获得相同的结果...每次查看for循环示例时,我的大脑都会朝上翻转。 我确定我已经使整个事情复杂化了,但是我已经将这个问题塞了几个小时了,我想我在大脑中的某个地方炸毁了抵抗者。
有趣的是,作为最佳实践,您不应该在数组上使用for ... in循环,否则可能会惹上麻烦。 常规的for循环很好 ,但是对于您的情况,我建议对数组本身使用.forEach()
方法 ,如下所示:
var array = ['foo', 'bar', 'baz'];
array.forEach(function (element, index, array) {
console.log(element, index, array);
}
这是与jQuery的.each()
非常相似的方法,该方法应使转换更直接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.