Today, record the two-bit array of JS and attach an example.
I. The nature of a two-dimensional array: The elements in the array are also arrays.
In fact, we have all seen such a two-dimensional array, just don't care about it, for example:
var arr = [[[1,2,4,6],[2,4,7,8],[8,9,10,11],[9,12,13,15]]//This is a two-bit array
ARR[2][3]; 11 Note: Represents the element that contains the 4th row of the third column. Angle label starting from 0
Two. The following describes the initialization of a two-dimensional array
Remembering the nature of the two-dimensional array, initialization is hard for us. Take a look at the example
Example one:
var arr = [[1,2],[a,b]]; Alert (arr[1][0]); element of row 1th of column A 2nd
Example two:
Declaration of an instance 3:2-dimensional array:
var arr = new Array (); First declare one-dimensional for (Var i=0;i<5;i++) { //one-dimensional length of 5 arr[i]=new Array (); In the declaration two-dimensional for (Var j=0;j<5;j++) { //two-D length is 5 arr[i][j]=1;
Then, traverse the two-dimensional array arr
for (Var i=0;i<arr.length;i++) {for (Var j=0;j<arr[i].length;j++) {document.write (arr[i][j]); } document.write ("<br/>"); Results
Note: We write a newline that is written to the label because Document.Write () is written to the HTML document. So writing a newline cannot be "\ n".
Example: In a two-dimensional array, each row is ordered in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Complete a function, enter such a two-dimensional array and an integer to determine if the array contains the integer
var arr = [[1,2,4,6],[2,4,7,8],[8,9,10,11],[9,12,13,15]]; Rule: First select the number in the upper-right corner of the array, if the number = the number to look for, the search process is finished, if the number > to find the number, exclude the column in which the number is located;//If the number < The number to find, reject the line where the number is located. function Find (Arr,num) {if (num==undefined) {Console.log (num+ "is null"); Return } while (num!=undefined&&arr.length) {var temp = arr[arr.length-1][0]; if (num = = temp) {Console.log (num+ "is finded"); return temp; }else if (temp>num) {arr.pop (); if (arr.length = = 1) {console.log (num + "is NOT exists," +num+ "was less the MinValue"); Return }}else{for (Var i=0;i<arr.length;i++) {if (Arr[i].length ==1) { Console.log (num + "is NOT exists," +num+ "are more than the MaxValue"); Return } arr[i].shift (); }}}} var result = find (arr,undefined); Console.log (result);
A two-dimensional array of JS