简体   繁体   English

创建二维数组Javascript

[英]Creating a 2d Array Javascript

How can I create a 2d array in javascript and load it with the values from user input? 如何在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);

How to create a 2D array: How can I create a two dimensional array in JavaScript? 如何创建2D数组: 如何在JavaScript中创建二维数组?

Loading values from user input: essentially use 从用户输入加载值:本质上使用

b[0][0] = myInput00;
b[0][1] = myInput01;

...etc. ...等等。 etc. 等等

It may be more structured to use for-loops, ie 使用for循环可能会更结构化,即

for (var i=0;i<input.length;i++)
{ 
    for (var j = 0; j < input.height; j++)
    {
        b[i][j] = input[i][j];
    }
}

with input[i][j] replaced with however your input is formatted. 用input [i] [j]替换为您的输入格式。 The answer clearly varies slightly depending on the input format, but that's the general pattern. 答案显然会略有不同,具体取决于输入格式,但这是一般模式。

Edit: if the input is a fixed 3x3 box, you might just assign all the table cells as individual divs or spans, and allocate each of the array indices (b[0][0], b[0][1] etc.) in turn. 编辑:如果输入是固定的3x3框,则可以将所有表单元格分配为单独的div或span,并分配每个数组索引(b [0] [0],b [0] [1]等。 ) 反过来。

Multi-dimensional arrays in many languages are just arrays within arrays. 许多语言中的多维数组只是数组中的数组。

// 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"

Therefore, making a 3 by 3 matrix can be done like this: 因此,可以像这样制作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)+"] = ?");
  }
}

(Of course, this is not the best way to do, but it is the easiest way to follow.) (当然,这不是最佳方法,但这是最简单的方法。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM