试图以正确的方式学习For循环

我最近一直在教我自己的Node.JS,它很有趣。 不过,我已经遇到了一个在这里真正杀了我的路障。 我已经认识到,我不能把我的头绕在JS的循环。 每当我去使用循环,我最终只是使用jquery $ .each()来省下我的头。 那么我不能依靠。每个我试图和我卡住试图把我的头围绕For循环。 这是我正在与之合作。

只是在一些情况下,我一直在使用node.js中的websockets。 其乐无穷! 我开始使用在任何地方都可以find的标准ChatApp,现在我正在尝试构build一个多人游戏Tic-Tac-Toe。 当玩家点击网格时,网格select被存储在node.js websocket服务器上的玩家对象内的列表中。

我试图做的最后一件事就是将所选电路板节点的列表与可能的井字棋解决scheme的主列表进行比较:

//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中testing了一段时间,似乎按照我的想法工作,除了缺less.each serverside!

那么我怎样才能达到同样的效果?每当我看到一个for循环的例子,我的大脑就变成了一面倒。 我肯定我已经把这个事情搞得一团糟了,但是现在我已经连续几个小时了,我想我在我脑中的某个地方吹了一个电阻。

有趣的是,作为一个最佳实践,您不应该在数组中使用for … in循环 ,这可能会让您陷入困境。 一个常规的for循环是好的 ,但是对于你的情况,我build议在数组本身上使用.forEach()方法 ,就像这样:

 var array = ['foo', 'bar', 'baz']; array.forEach(function (element, index, array) { console.log(element, index, array); } 

这是一个非常类似于jQuery的.each() ,这应该使转换更直接。