JavaScript 循环遍历 .children() 项并保存到数组

javascript loop through .children() items and save to array

本文关键字:保存 数组 循环 遍历 children JavaScript      更新时间:2023-09-26

关于这个问题,我找不到任何适合我的解决方案,所以如果重复,请原谅我。

我想遍历所有 .children() 项目,如果其中一些项目满足条件,我想将这些项目保存在一个数组中。这是准确显示我的意思的代码:

    var items = [],
        allitems = $('.iconImg').children(),
        obj;

    // console.log(allitems);
    $('#next4').on('click', function(e){
        e.preventDefault();
        for(var i=0; i<allitems.length; i++){
            var currItem = $(allitems[i]).attr('id'),
                currItemPosLeft = parseInt($('#'+currItem).css('left')),
                itemOffset = getOffset('#'+currItem),
                items = [],
                arrToSend = [];
                // console.log(currItem, '=>', currItemPosLeft);    
            if(currItemPosLeft >= 405){
                obj = {
                    obId: currItem,
                    obPos: itemOffset
                }

                items.push(obj);
                console.log(items);
            }                   

        }

这段代码为我提供了满足条件的对象的数组数量,但我想要的是一个数组来存储这些对象。

我该怎么做?

谢谢

好的,我解决了。我不知道为什么我这么复杂,这超级容易。
因此,代码将是:

    var items = [],
    allitems = $('.iconImg').children().toArray(),
    obj;

    // console.log(allitems);
    $('#next4').on('click', function(e){
        e.preventDefault();
        $(allitems).each(function(i){
            var currItem = $(allitems[i]).attr('id'),
                currItemPosLeft = parseInt($('#'+currItem).css('left')),
                itemOffset = getOffset('#'+currItem);

            // console.log(currItem, '=>', currItemPosLeft);
            obj = {
                odId: currItem,
                obPos: itemOffset
            };
            if(currItemPosLeft >= 405){
                items.push(obj);
            }


        })
        console.log(items);

    })
    //end of #next4 click

只是一个做事的演示;

var testData = [{id:1,data:'abc'},{id:2,data:'efg'},{id:3,data:'pqr'},{id:4,data:'xyz'}]
var res = []
testData.forEach(function(o){ 
       if(o.id % 2 == 0) { //your condition..
          res.push({nid:o.id, ndata: o.data}) 
       } 
});

演示:http://jsfiddle.net/dpst36xe/