简体   繁体   中英

How to get the cell value in 2D array in Javascript

How to get the cell value in 2D array in Javascript

I have a table of numbers, which will 31 cols * 9 rows, I want to get the cell value from getting the spot function! so I want [1][2].the important value for me is Y only? how to pass theGrid to the spot function? also, any suggestions for performance will be fantastic as you can see the it is huge array

    var cols = 31;
    var rows = 9; 
    var theGrid = new Array(cols);
    var i;
    var j;
    //get the spot
    function getTheSpot(j, i) {
      // when the col met the row it create a spot
      //that what i need to get 
        this.y = i;
        this.x = j;
        return i;
        return j;
    }

    //create a grid for the numbers 
    function createGrid() {
        // BELOW CREATES THE 2D ARRAY 
       for (var i = 0; i < cols; i++) {
           theGrid[i] = new Array(rows);
         }

         for (var i = 0; i < cols; i++) {

           for (var j = 0; j < rows; j++) {
                theGrid[j][i] = new getTheSpot(j, i);

            }
        } 

    } 
    var s = getTheSpot(9, 2);
    console.log (s);

If I understand what you need correctly, you can reference an array element like this:

var your_array = [ 10, 11, 15, 8 ];

// Array indexes start at 0
// array[0] is the the first element
your_array_name[0] == 10
//=> true

// array[2] is the third element
your_array_name[2] == 15
//=> true

Now, on 2D matrixes (arrays inside an array), here's how things go:

var awesome_array = [
    [ 0, 10, 15, 8 ],
    [ 7, 21, 75, 9 ],
    [ 5, 11, 88, 0 ]
];

// Remember the index starts at 0!

// First array, first element
awesome_array[0][0] == 0
//=> true

// Second array, fourth element
awesome_array[1][3] == 9
//=> true

In your case, you (supposedly) have this layout:

var greatest_array = [
    [ "A", "B", "C", "D", "E", "F" ],
    [ "B", "C", "D", "E", "F", "G" ],
    [ "C", "D", "E", "F", "G", "H" ]
];

// Your desired "E" is on the second array (index 1), fourth line (index 3):
console.log(greatest_array[1][3]);  //=> "E"

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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