简体   繁体   English

坚持创建一个有效的 javascript 循环

[英]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.我有 7 列,编号为 0 - 6。每列包含几个 DIV。 I want to find the last div in each column.我想在每一列中找到最后一个 div。 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): Atm 我对每列进行了以下编码 7 次(其中 cols[1] 变为 cols[2] 等):

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:作为菜鸟/初学者编码员,我对它们没有太多经验,所以我从一个“for”循环开始:

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.这给了我所有的列 nrs。 Next step using the nrs to check each column for the lastDiv:下一步使用 nrs 检查每列的 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.这似乎不起作用,我没有得到每列的每个 lastDiv。 So I thought perhaps I need a "forEach" instead?所以我想也许我需要一个“forEach”来代替? 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).我还找到了一些“for of”的例子,但它们对我来说更复杂(尽管我读过使用这些例子很好)。

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!这对我有用!

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

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