[英]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.