簡體   English   中英

連續將數組添加到2D數組

[英]Continuously adding arrays to a 2D array

每次我單擊網格中的一個單元格時,它會將單元格的[行,列]數組記錄到一個變量中,即bla(黑色)或whi(白色)。 但是,下次單擊單元格時,它將更改變量。 例如,我單擊一個單元格,變量whi是[1,2],然后單擊另一個單元格,變量bla是[2,2],然后,我單擊第三個單元格,變量whi從[1] ,2](從原始點擊)到[3,2]。 (我為此做了隨機數)。 我想創建兩個2D數組,一個用於變量bla,一個用於變量whi。 以我的示例為例,2D數組之一應為[[1,2 ,, [3,2]](用於白色單元格),另一個應為[[2,2]](對於黑色單元格)

測試代碼:

 var white=true; function generateGrid( rows, cols ) { var grid = "<table>"; for ( row = 1; row <= rows; row++ ) { grid += "<tr>"; for ( col = 1; col <= cols; col++ ) { grid += "<td></td>"; } grid += "</tr>"; } return grid; } $( "#tableContainer" ).append( generateGrid( 10, 10) ); $( "td" ).click(function() { $(this).css('cursor','default'); var index = $( "td" ).index( this ); var row = Math.floor( ( index ) / 10) + 1; var col = ( index % 10) + 1; var $td = $(this); if ($td.data('clicked')) return; if (white===true){ var whi=[row,col]; //I want to log the array for whi into a 2D array console.log("white coord is "+whi); } else { var bla=[row,col]; //I want to log this array into another 2D array console.log("black coord is "+bla); } $td.data('clicked', true); $td.css('background-color', white ? 'white' : 'black'); white = !white; }); 
 html{ background-color:#7189ea; } td { border: 1px solid; width: 25px; height: 25px; border-radius:100%; } table { border-collapse: collapse; } 
 <link type="text/css" rel="stylesheet" href="stylesheet.css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div id="tableContainer"></div> 

whibla初始化為數組,然后將[row,col]推送到它們-請參見下面的演示:

 var white = true; var whi = []; var bla = []; function generateGrid(rows, cols) { var grid = "<table>"; for (row = 1; row <= rows; row++) { grid += "<tr>"; for (col = 1; col <= cols; col++) { grid += "<td></td>"; } grid += "</tr>"; } return grid; } $("#tableContainer").append(generateGrid(10, 10)); $("td").click(function() { $(this).css('cursor', 'default'); var index = $("td").index(this); var row = Math.floor((index) / 10) + 1; var col = (index % 10) + 1; var $td = $(this); if ($td.data('clicked')) return; if (white === true) { whi.push([row, col]); } else { bla.push([row, col]); } $td.data('clicked', true); $td.css('background-color', white ? 'white' : 'black'); white = !white; }); $('#getarr').click(function(){ console.log("white arr: ", whi); console.log("black arr: ", bla); }); 
 html { background-color: #7189ea; } td { border: 1px solid; width: 25px; height: 25px; border-radius: 100%; } table { border-collapse: collapse; } 
 <link type="text/css" rel="stylesheet" href="stylesheet.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div id="tableContainer"></div> <button id="getarr">Get array</button> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM