简体   繁体   中英

Javascript looping only through defined properties of array. How?

For example if i'm keeping array of references via id like that:

if(typeof channel_boards[misc.channel_id] == 'undefined') {

    channel_boards[misc.channel_id] = $('<div class="channel" channel_id="'+misc.channel_id+'"></div>').appendTo('#board');
}

And then i'm looping through array to find required reference. I'm looping through undefined properties as well. Is it possible to loop only through defined properties?

for(i=0;i<channel_boards.length;i++)
{
    if(channel_boards[i] != undefined)
    {
        if(channel_boards[i].attr('channel_id') != visible) {channel_boards[i].addClass('hidden_board');}
        else {channel_boards[i].removeClass('hidden_board');}       
    }
}

Maybe i should change the way i'm storing references? Via object for example, but how i'll be able to find proper reference via id number.

It does sound like you would be better of using an object to store the references

var channel_boards = {};
var channel_id = 1;
// add property
channel_boards["channel_" + channel_id] = ......

// enumerate properties
for (var key in channel_boards) {
    if (channel_boards.hasOwnProperty(key) {
        channel_boards[key].attr(......
    }
}

// delete property
delete channel_boards["channel_" + channel_id];

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