junikear
junikear

Reputation: 85

JavaScript simplify for loop

I built the following for Loop and wanted to ask if there is a way to simplify it:

//data contains an array
var i = 0;
if(data.length >= 1) {
    i = 1;
}
for (i; i <= data.length; i++) {
    $('#img-thumb-id' + i).attr('src', data[i-1]);
}

Upvotes: 1

Views: 1277

Answers (5)

Dhananjaya Kuppu
Dhananjaya Kuppu

Reputation: 1322

You may also try this :

data.forEach(function(item, index){
   $('#img-thumb-id' + (index+1)).attr('src', item);
});

Upvotes: 1

Adam Azad
Adam Azad

Reputation: 11297

I see that jQuery is used here, so you can use $.each

$.each(data, function(i, item){

   var iteration = +i+1;
   $('#img-thumb-id' + iteration).attr('src', item);

});

if you want to use vanilla JavaScript (no jQuery at all)

for (var i; i < data.length; i++) {
   var iteration = +i+1;
   document.getElementById('img-thumb-id'+iteration).src = data[i];
}

Or you can use:

for (var i in data) {
   document.getElementById('img-thumb-id'+(+i+1)).src = data[i];
}

Upvotes: 3

Krazy_Tech
Krazy_Tech

Reputation: 316

Use simple foreach loop in JavaScript

//for eg. data array may be
var data = [1,2,3,4];
data.forEach(function(item, index){
$('#img-thumb-id' + (index+1)).attr('src', item);
});

Upvotes: -1

Jack F.
Jack F.

Reputation: 154

The loop is fine, but I don't see why you don't just do:

if(data !== null){
    for (var i = 0; i < data.length; i++) {
                $('#img-thumb-id' + (i + 1)).attr('src', data[i]);
            }
}

You don't need to do the first block of code in your question. It is more clear to people reading your code if you just do a standard for-loop starting from 0 and going up to the object.length.

Upvotes: 1

sjahan
sjahan

Reputation: 5950

if(typeof data!=="undefined" && data && data.length>0) {
    for (var i=0; i < data.length; i++) {
        $('#img-thumb-id' + (i+1)).attr('src', data[i]);
    }
}

Upvotes: 1

Related Questions