[英]Creating a 2d Array Javascript
如何在javascript中創建2d數組並將其與用戶輸入的值一起加載?
var b;
b = new Array( 3 ); // allocate rows
b[ 0 ] = new Array( 3 ); // allocate columns for row 0
b[ 1 ] = new Array( 3 ); // allocate columns for row 1
b[2]= new Array(3);
如何創建2D數組: 如何在JavaScript中創建二維數組?
從用戶輸入加載值:本質上使用
b[0][0] = myInput00;
b[0][1] = myInput01;
...等等。 等等
使用for循環可能會更結構化,即
for (var i=0;i<input.length;i++)
{
for (var j = 0; j < input.height; j++)
{
b[i][j] = input[i][j];
}
}
用input [i] [j]替換為您的輸入格式。 答案顯然會略有不同,具體取決於輸入格式,但這是一般模式。
編輯:如果輸入是固定的3x3框,則可以將所有表單元格分配為單獨的div或span,並分配每個數組索引(b [0] [0],b [0] [1]等。 ) 反過來。
許多語言中的多維數組只是數組中的數組。
// Create an array with 4 elements.
var b = [1, [2, 3], [4, [5, 6], 7], 8];
console.log(b.length); // 4
// Looping through arrays
for(var i=0; i<b.length; i++){
// b[0] = 1
// b[1] = [2, 3]
// b[2] = [4, Array[2], 7]
// b[3] = 8
console.log("b["+i+"] =", b[i]);
}
// Since b[1] is an array, ...
console.log(b[1][0]); // First element in [2, 3], which is 2
// We can go deeper.
console.log(b[2][1]); // [5, 6]
console.log(b[2][1][0]); // 5
// We can change entries, of course.
b[2][1][0] = 42;
console.log(b[2][1][0]); // 42
b[1] = ['a', 'b', 'c'];
console.log(b[1][0]); // "a"
因此,可以像這樣制作3 x 3矩陣:
var b = [];
for(var i=0; i<3; i++){
b[i] = [];
for(var j=0; j<3; j++){
b[i][j] = prompt("b["+(i+1)+","+(j+1)+"] = ?");
}
}
(當然,這不是最佳方法,但這是最簡單的方法。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.