简体   繁体   中英

Javascript array inside of another array (multidimensional)

I have an array

cells = [0, 0, 0, 0, 0, 0, 0, 0, 0];

which is updated with a jQuery function

 $(document).ready(function(){
...
    $('#box').click(function(e){

        var indexArray = e.target.id.split('_');

        if (indexArray.length > 1) {
            var index = indexArray[1];

            if (cells[index] == 0){
                cells[index] = move;
...
})

I want to make a cross-check of cells array groups. for example:

(cells[0] + cells[1] + cells[2]);   // row 1
(cells[3] + cells[4] + cells[5]);   // row 2
(cells[6] + cells[7] + cells[8]);   // row 3
...

I tried to create a multidimensional array, but all I get is undefined:

var triggers = [[cells[0], cells[1], cells[2]]];

is it possible to pass cells arrays' variables to triggers array? Can't figure it out?!

You can use slice to get part of an array, for example

var triggers = [cells.slice(0, 3)];

The call cells.slice(0, 3) returns an array with the elements of cells starting from index 0 up to and excluding 3 , ie [cells[0], cells[1], cells[2]] . You can wrap another array over that "manually" to get the desired result.

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