Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A quite weird array [closed]

Here is my problem, I'm programming a game and I need to use a very simple array, the problem is that I create it, everything's ok, and the next line, the values of an entire line in the array change and I don't understand why, here is my code :

var ciblesPossibles = new Array();

    for (var i = 0; i < 2; i++) {
        for (var j = 0; j < 5; j++) {
            ciblesPossibles[i,j] = 1 + portee(i, j, ID, pos, carte.effet.portee) + duBonCote(i, ID, carte.effet.ciblesLegales);
        }
        console.log('1/ ciblesPossibles['+i+',x] = ' + ciblesPossibles[i,0] + ciblesPossibles[i,1] + ciblesPossibles[i,2] + ciblesPossibles[i,3] + ciblesPossibles[i,4]);
    }


    for (i = 0; i < 2; i++) {
        console.log('2/ ciblesPossibles['+i+',x] = ' + ciblesPossibles[i,0] + ciblesPossibles[i,1] + ciblesPossibles[i,2] + ciblesPossibles[i,3] + ciblesPossibles[i,4]);
    }

    var max = maxTab(ciblesPossibles);

    for (i = 0; i < 2; i++) {
        for (j = 0; j < 5; j++) {
            ciblesPossibles[i,j] = Math.floor(ciblesPossibles[i,j] / max);
            console.log(ciblesPossibles[i,j]);
        }
    } 

portee() and duBonCote() are two functions which return just 1 or 0. When I'm at the console.log('/1...'), I have something like 33222 and 22211 (it's what I want), but when I'm at the console.log('/2...'), I have 22211 and 22211 ... What can make the first line change in my array ?

Regards

like image 672
Kahsius Avatar asked Jul 16 '26 07:07

Kahsius


1 Answers

Two dimensional arrays are accessed as a[i][j], not a[i,j].

The latter will be treated as a use of the comma operator, and evaluates to just a[j], i.e. a one-dimensional matrix.

You'll be wanting something more like:

var ciblesPossibles = [];   // create array to hold rows - NB: not "new Array():
for (var i = 0; i < 2; i++) {
    ciblesPossibles[i] = [];    // create the individual row
    for (var j = 0; j < 5; j++) {
        ciblesPossibles[i][j] = ...
    }
}
like image 134
Alnitak Avatar answered Jul 17 '26 19:07

Alnitak