简体   繁体   中英

Stuck with creating a working javascript loop

I am struggling with the following:

I have 7 columns numbered 0 - 6. Each column contains several DIV's. I want to find the last div in each column. I can get them using:

var lastDiv = col[col.length-1];
console.log(lastDiv); 

Atm I have the following per column coded 7 times (where cols[1] becomes cols[2] etc):

var col = cols[1]; //setting the second column
var lastDiv = col[col.length-1];
console.log(lastDiv);

So to safe coding space I though this could also be done using a loop. As a noob/beginner coder I have not much experience with them so I started simple with a "for" loop:

function myFunction(){
    var col = [ 0, 1, 2, 3, 4, 5, 6 ];
         for (var i = 0; i <= 6; i++) {
            console.log(col[i]);
         }
}

This gives me all the column nrs. Next step using the nrs to check each column for the lastDiv:

function myFunction(){
    var col = [ 0, 1, 2, 3, 4, 5, 6 ];
         for (var i = 0; i <= 6; i++) {
            var lastDiv = col[col.length-1];
            console.log(lastDiv);
         }
}

This doesn't seem to work, I don't get each lastDiv per column. So I thought perhaps I need a "forEach" instead? So I've tried:

var col = [ 0, 1, 2, 3, 4, 5, 6 ];
    col.forEach(myFunction);

    function myFunction(){
        var lastDiv = col[col.length-1];
        console.log(lastDiv);
     }

This didn't work either. I also found some "for of" examples, but they were even more complex to me (though I've read it's good to use these).

Obviously, I am doing something wrong here, but I can't seem to figure it out. So I thought about asking here. What am I missing/doing wrong?

Thanks

Try this method

$('col selector').each(function(e){
let lastdiv =$(this).children().last('div');
});

Got it figured out (I didn't need to use the array):

function myFunction(){
        for (var i = 0; i <= 6; ++i) {
            var col = cols[i];
            var lastDiv = col[col.length-1];
//some other stuff
}

This worked for me!

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