JavaScript > 1次元の配列を2次元へ変換
1次元の配列データを2次元配列へ格納。
by s_hiroshi
HTML
<link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css">
<h1 id="qunit-header">QUnit example</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">test markup, will be hidden</div>
CSS
td {
padding: 3px 5px;
border: 1px solid #999;
}
table {
margin: 20px;
}
JavaScript
module("1次元配列のデータを2次元配列へ格納する。", {
setup: function() { // 初期化処理
}
});
test('test', function() {
var arr = [3, 2, 1, 1, 2, 1, 3, 2, 1, 2];
var rows = 5;
var cols = 2;
ok('ok');
var matrix = toMatrix(rows, cols, arr);
console.log(matrix);
});
// 1次元配列を2次元配列へ
function toMatrix(rows, cols, linear) {
var i, j, matrix = [];
for (i = 0; i < rows; i++) {
matrix[i] = [];
for (j = 0; j < cols; j++) {
matrix[i][j] = linear[i * cols + j];
}
}
return matrix;
}