简体   繁体   English

向Javascript数组添加对象

[英]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 我希望打印出的是,第4列7行5列7行6列7行7列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. 我试图根据背景颜色记录表格的x和y坐标,如果红色介于黑色之间,则将vblack数组设置为0。

Move the console.log loop outside the assignment loop. console.log循环console.log分配循环之外。

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. 使用Javascript数组需要注意的一点是,索引并不总是顺序的。 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. 很高兴想到vblack总是有0-n个元素,但并非总是如此,.length将报告n + 1个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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