JavaScript中的2D数组

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers.

本文介绍如何在JavaScript中创建和访问二维数组。 它包括一个教程,以防您只是试图“缠住脑袋”这个概念,并且我们还将研究一些针对高级程序员的有用技巧。

介绍
(Introduction
)

2D数组是信息矩阵。 每个元素都有两个索引:行( y) and a column ( x).   A matrix is handy whenever you have rows and columns of data.  For instance, if you need to output a month-by-month amortization table, you probably want to show it with a row for each year and a column for each month.  If you have a company sales chart, you might have a matrix with each regional branch represented as a row and have columns to break down sales for widgets, gadgets and gizmos.
Checkerboard as an array

Think of a chessboard.  There are 8 rows (numbered 0,1,...7) and 8 columns (also 0,1,...7). If you want to check what piece is on the top left corner, you access chessboard[0][0].  The next square to the right of that is [0][1], varying the x value until you get to [0][7] as you go left-to-right.  Vary the y value to move from the top to the bottom; for instance, [6][1] is the second square on the seventh row.

想想一个棋盘。 有8行(编号为0,1,... 7)和8列(也为0,1,... 7)。 如果要检查左上角的棋子 ,请访问棋盘[0] [0] 。 右边的下一个正方形是[0] [1] ,改变[0] [7] 。 改变[6] [1]是第七行的第二个正方形。

The notation I'm using matches that of JavaScript -- two sets of bracketed integers: [y][x]  All arrays start with element 0; the easy way to think of that is "how much distance from the left" a "distance of 0" means exactly at the left.

我使用的表示法与JavaScript的表示法相匹配-两组带括号的整数: [ 所有数组均以元素0开头; 简单的思考方式是“

Another convention when talking about a matrix is the use of "generic" variable names x and y.  In such discussions, x is always the column index (distance from the left) and y is the row index (distance from the top).  So a y,x of [0][0] identifies the item at the top left.  [0][1] is the second item on the top row, [1][n] is on the second row and so forth.

在讨论矩阵时,另一种约定是使用“通用”变量名称 。 在此类讨论中,

JavaScript和2D数组
(JavaScript and 2D Arrays
)

严格来说,JavaScript不支持2D数组。 处理2D矩阵中数据的通常方法是创建一个Array对象,其中每个元素本身就是一个Array对象。 我们一分钟就会解决。 Use a 1D Array As If It Were a 2D Array使用一维数组,就好像它是二维数组一样

It is possible to coerce a 1D array into a 2D array, using programming logic.  We'll touch on this lightly here.  It's interesting, but you might not need to use it in your day-to-day programming.

使用编程逻辑可以将1D数组强制转换为2D数组。 我们将在这里对此轻描淡写。 这很有趣,但是您可能不需要在日常编程中使用它。

Let's say you have a string of letters:

假设您有一串字母:

var sData= "abcdefghijABCDEFGHIJäß©ÐëØ>½îÿ";
// column:  0123456789 
var sData= "abcdefghij"  // row 0 (starts at offset 0)
          +"ABCDEFGHIJ"  // row 1 (starts at offset 10)
          +"äß©ÐëØ>½îÿ"  // row 2 (starts at offset 20)

   (y * row_length) + x

where y is the row index, x is the column index, and row_length is the number of columns in each row.

其中

1D array coerced into 2D layout
impose a 2D structure on it using program logic:
// assumes data is a string, sData and rows have 10 columns
function GetCellValue(y,x) {
   nRowStart= y*10;
   nOffset = nRowStart+ x;
   sElementValue= sData.substr(nOffset,1); // access one element   
   return( sElementValue );  
}
....
//                  y,x (row, column)
alert( GetCellValue(0,0) ); // displays a
alert( GetCellValue(0,1) ); // displays b
alert( GetCellValue(0,2) ); // displays c
alert( GetCellValue(1,2) ); // displays C
alert( GetCellValue(2,2) ); // displays ©
alert( GetCellValue(0,9) ); // displays j
alert( GetCellValue(1,9) ); // displays J
alert( GetCellValue(2,9) ); // displays ÿ

正常使用:数组数组
(Normal Usage: Array of Arrays
)

在JavaScript中使用2D数组的通常方法是创建一个1D数组,并将其中的每个元素设置为 another 1D array.   Straightforward Assignment直接分配

The following is one way to create and populate a 2D array:

以下是创建和填充2D数组的一种方法:

as2D= new Array(); // an array of "whatever"
as2D[0]= new Array("a","b","c","d","e","f","g","h","i","j" );
as2D[1]= new Array("A","B","C","D","E","F","G","H","I","J" );
as2D[2]= new Array("ä","ß","©","Ð","ë","Ø",">","½","î","ÿ" );
alert( as2D[0][0] ); // displays a
alert( as2D[2][2] ); // displays ©
alert( as2D[2][9] ); // displays ÿ
2D array is really an array of Array objects

Use Brackets [...] As a Shorthand

使用括号作为速记[...]

The syntax

语法

  var a= [ item0, item1, item2, ... ];

var a = [

is shorthand for

是的简写

  var a= new Array( item0, item1, item2, ... );

var a = new Array(

That is,

那是,

  []            represents a new array with 0 elements,

[]代表一个包含0个元素的新数组,

  ["a"]       represents a new array with 1 string element,

[“ a”]代表一个带有1个字符串元素的新数组,

  ["a","b"] represents a new array with 2 string elements,

[“ a”,“ b”]表示一个具有2个字符串元素的新数组,

and so forth.  Thus, a cool way to setup and populate our example array is:

等等。 因此,设置和填充示例数组的一种很酷的方法是:

var as2D = [ 
    ["a","b","c","d","e","f","g","h","i","j"], 
    ["A","B","C","D","E","F","G","H","I","J"], 
    ["ä","ß","©","Ð","ë","Ø",">","½","î","ÿ"] 
];

    as2D[n]= new Array( a,b,c,... )

as2D [

syntax that we used before.  You access the data the same way.

我们之前使用的语法。 您以相同的方式访问数据。

Use the Array.push() Method

使用Array.push()方法

The push() method of the Array object adds a new element (or elements) to the end.  Since it is common to populate an array starting from the top, you can use syntax like:

Array对象的push()方法在末尾添加一个或多个新元素。 由于通常从顶部开始填充数组,因此可以使用如下语法:

var as2D = new Array();
as2D[0] = new Array();
as2D[0].push( "a" );
as2D[0].push( "b" );
as2D[0].push( "c","d","e","f","g","h","i" );
as2D[0].push( "j" );
as2D.push( new Array( "A","B","C","D","E","F","G","H","I","J" ) );
as2D.push( [ "ä","ß","©","Ð","ë","Ø",">","½","î","ÿ" ] ); 

Note that the push() method lets you push a single item (as in lines 3, 4, and 6) or a series of items (line 5).  Lines 7 and 8 push entire arrays into the top-level array.  Here's how it looks without the extra illustrative lines:

请注意,push()方法使您可以推送单个项目(如第3、4和6行 )或一系列项目( 第5行 )。 第7和8行将整个数组推入顶层数组。 没有多余说明行的外观如下:

var as2D= []; // or: new Array();
as2D.push( ["a","b","c","d","e","f","g","h","i","j"] );
as2D.push( ["A","B","C","D","E","F","G","H","I","J"] );
as2D.push( ["ä","ß","©","Ð","ë","Ø",">","½","î","ÿ"] ); 

Use the String.split() Method

使用String.split()方法

The split() method of the JavaScript String object returns an Array object.  It is very often used in populating an Array with predefined values.  

JavaScript String对象的split()方法返回一个Array对象。 它非常常用于用预定义值填充数组。

var sData1= "a,b,c,d,e,f,g,h,i,j";
var sData2= "A,B,C,D,E,F,G,H,I,J";
var sData3= "ä,ß,©,Ð,ë,Ø,>,½,î,ÿ";

var as2D= []; // or: new Array();
as2D[0]= sData1.split(",");
as2D[1]= sData2.split(",");
as2D[2]= sData3.split(",");
var sData1= "abcdefghij";
var sData2= "ABCDEFGHIJ";
var sData3= "äß©ÐëØ>½îÿ";

var as2D= []; // or: new Array();
as2D[0]= sData1.split("");
as2D[1]= sData2.split("");
as2D[2]= sData3.split("");
var as2D= []; 
as2D[0]= "abcdefghij".split("");
as2D[1]= "ABCDEFGHIJ".split("");
as2D[2]= "äß©ÐëØ>½îÿ".split("");
var as2D= "abcdefghij,ABCDEFGHIJ,äß©ÐëØ>½îÿ".split(",")
as2D[0]=as2D[0].split("");
as2D[1]=as2D[1].split("");
as2D[2]=as2D[2].split("");
var as2D= [
    "abcdefghij".split(""),
    "ABCDEFGHIJ".split(""),
    "äß©ÐëØ>½îÿ".split("")
];
var declaration is just another piece of procedural code that gets executed at runtime.

处理二维阵列
(Processing a 2D Array
)

for Loops

When you boil it all down, the main reason for creating and using a 2D array is so that at some point in your program, you can use a nested loop sequence like:

当您将其全部煮沸后,创建和使用2D数组的主要原因是可以在程序中的某个点上使用嵌套循环序列,例如:

for ( var y=0; y<3; y++ ) {
    for ( var x=0; x<10; x++ ) { 
       // do something with myArray[y][x]
    }
}
var sOut="<table border=2>";
for (var y=0; y<as2D.length; y++ ) {        // for each row
    sOut += "<tr>";
    for (var x=0; x<as2D[y].length; x++ ) { // for each clm
        sOut += "<td>" + as2D[y][x] + "</td>";
    }
    sOut += "</tr>";
}
sOut += "</table>";
Output of code that cycle both dimensions of the 2D array
var nClmsPerRow= as2D[0].length;      // assume same length
for ( var x=0; x<nClmsPerRow; x++ ) {  // for each row
    sOut += "<tr>";
    for ( var y=0; y<as2D.length; y++ ) { // for each clm
       sOut += "<td>" + as2D[y][x] + "</td>";
    }
    sOut += "</tr>";
}
Switcheroo -- treat rows as columns (and vice-versa)

Nested for...in loops

为...嵌套

JavaScript also provides a specialized for-loop construct that iterates through an Array.  It is the for... in statement.  Using it simplifies the code a bit since it knows the loop-terminating condition (the end of the array).  It's used with collections and Arrays.  With Arrays, the syntax is:

JavaScript还提供了一个专门的for循环构造,可循环访问Array。 这是

    for ( nIdxVar in aArray )

为(

Each loop sets nIdxVar to the index of that iteration (0, 1, 2,...).  It stops looping when it gets to the end of the array.  Here's some code that accesses all items in our example 2D array:

每个循环将

for ( y in as2D ) {
   for ( x in as2D[y] ) {
       // do something with as2D[y][x];
   }
}

for...in comes when you have a sparse array ; that is, when some of the elements are undefined.  For instance:

因为...当您有一个

var aSparse= new Array;
aSparse[0]= ["zero",  "one",       "two"      ];
aSparse[4]= [      ,  "forty-one",            ];
aSparse[5]= ["fifty", "fifty-one", "fifty-two"];

for ( y in aSparse ) {
   for ( x in aSparse[y] ) {
       alert("y,x=(" +y+ "," +x+ ") value: " + aSparse[y][x] );
   }
}

   y,x=(0,0) value: zero

y,x =(0,0)值:零

   y,x=(0,1) value: one

y,x =(0,1)值:1

   y,x=(0,2) value: two

y,x =(0,2)值:两个

   y,x=(4,1) value: forty-one

y,x =(4,1)值:41

   y,x=(5,0) value: fifty

y,x =(5,0)值:五十

   y,x=(5,1) value: fifty-one

y,x =(5,1)值:五十一

   y,x=(5,2) value: fifty-two

y,x =(5,2)值:52

2D阵列与对象集合
(2D Array vs. Collection of Objects
)

2D数组非常适合表示相同数据元素的矩阵。 例如,棋盘是8x8的正方形矩阵,屏幕是1680x1050的像素矩阵。 这种 x-by-y matrices come into use often in advanced JavaScript programming.  

But an even more common scenario is a 1D array that is a list of groups of different items.  That includes such often seen constructs as a database recordset, lists of <input> objects on a webpage, data related to items in a shopping cart, and so forth.

但是,更常见的情况是一维数组,它是一

In my next installment, well look at some fundamental aspects of such collections of data and how to create and use them in JavaScript.  See:

在我的下一部分中,将很好地研究此类数据的一些基本方面,以及如何在JavaScript中创建和使用它们。 看到:

Maps and Collections in JavaScriptJavaScript中的地图和集合

and

Sorting Arrays and Collections in JavaScript用JavaScript对数组和集合进行排序

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

=-=-=-=-=-=-=-=-=-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=

If you liked this article and want to see more from this author, please click the Yes button near the:

如果您喜欢这篇文章,并希望从该作者那里获得更多信息 ,请单击旁边的按钮:

      Was this article helpful?

本文是否有帮助?

label that is just below and to the right of this text.   Thanks!

此文字下方和右侧的标签。

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

=-=-=-=-=-=-=-=-=-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=

翻译自: https://www.experts-exchange.com/articles/3488/2D-Arrays-in-JavaScript.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值