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]);
}
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];
}
$('#img-thumb-id' + iteration) with document.getElementById('img-thumb-id'+iteration) I know the OP is using a jQuery selector but for future visitors it could be misleading or confusing as they will be expecting vanilla only.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]);
}
}
data and check the output, do the same for data being null,"",[],{} you will see some differences, to sum up this is more fail safe typeof data!=="undefined" && data && data.length i think if you really had the time to check the fiddle you would agree on that. Best regards.PHP's empty function what would you think of something like this jsfiddle.net/ftr46syd/2 ?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.
You may also try this :
data.forEach(function(item, index){
$('#img-thumb-id' + (index+1)).attr('src', item);
});
'#img-thumb-id' + index+1 ...won't produce what you expectUse 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);
});
$.each. And always start loop index from zero.