简体   繁体   中英

Adding object to Javascript array

I can not figure out why my objects have the same values, I think I am creating a new object every time.

for (i = row; i <= y; i++) {    
    if (t !== 0 && $('#' + i + '' + col).css('background-color') == 'rgb(0, 0, 0)') {
        console.clear(); //testing
        var obj = {
            rows: i,
            cols: col
        };
        vblack.push(obj);
        vred.length = 0;    

        //testing purposes only, printing contents of vblack array
        for (var j = 0; j < vblack.length; j++) {

            console.log("j " + j + " rows " + obj.rows + " col " + obj.cols);

        };

    } else if (t === 0 && $('#' + i + '' + col).css('background-color') == 'rgb(255, 0, 0)') {
        var obj = {
            rows: i,
            cols: col
        };
        vred.push(obj);
        vblack.length = 0;    
    }
}

Prints this to the console log

j 0 rows 7 col 7
j 1 rows 7 col 7
j 2 rows 7 col 7
j 3 rows 7 col 7

What I'm expecting to print out is, rows 4 col 7 rows 5 col 7 rows 6 col 7 rows 7 col 7

I'm trying to log x and y coordinates of a table depending on background color, if a red one is between black ones I set the vblack array back to 0.

Move the console.log loop outside the assignment loop.

for (i = row; i <= y; i++) {    
    if (t !== 0 && $('#' + i + '' + col).css('background-color') == 'rgb(0, 0, 0)') {
        var obj = {
            rows: i,
            cols: col
        };
        vblack.push(obj);
        vred.length = 0;    

    } else if (t === 0 && $('#' + i + '' + col).css('background-color') == 'rgb(255, 0, 0)') {
        var obj = {
            rows: i,
            cols: col
        };
        vred.push(obj);
        vblack.length = 0;    
    }
}

//testing purposes only
console.clear();
console.log("Black:");
for (var j = 0; j < vblack.length; j++) {
    console.log("j " + j + " rows " + vblack[j].rows + " col " + vblack[j].cols);
};
console.log("Red:");
for (var j = 0; j < vred.length; j++) {
    console.log("j " + j + " rows " + vred[j].rows + " col " + vred[j].cols);
};

Something to watch with Javascript Arrays, the index is not always sequential. Instead of

for( var j = 0....

prefer

for (j in vblack)

It's nice to think that vblack would have elements 0-n always, but it is not always the case and .length will report n+1.

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