繁体   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