JQBolo JQBolo - 1 month ago 4
jQuery Question

Jquery array loop

I am attempting to loop through the contents of an array in Jquery, the array contains a list of Place Names, followed by a URL ([0]name, [1]url, [2]name [3]url, etc.). The data for place names has been pulled through an API and as such some are undefined. Below is my loop in its current iteration.


for (var i=0; i<albums.length; i++){
if ((albums[i] != "undefined") && (albums[i+1].indexOf("http") !== 1)){
$("#thumbnail").css("overflow:", "auto");
$("#thumbnail").css("max-height:", "100px");
$("#thumbview").append('<div id="thumbnail"><img src='+[i+1]+' id="coverPhoto" height="320" width="420"></a></div>');
}
i++;
};



Below is the array as it is structured currently


Array[14]

[0]:"location name"[1]:"https:/..."[2]:"location name"[3]:"https:/..."[4]:"location name"[5]:"https:/..."[6]:"location name"[7]:"https:/..."[8]:undefined[9]:"https:/..."[10]:undefined[11]:"https:/..."[12]:"location name"[13]:"https:/..."


My goal for the loop is to check [i], if [i] is NOT undefined, then check [i+1] to see if it contains "http", if both conditions are true > build the image with the source from the array, and set the name and caption as location name.

in its current iteration it doesn't seem to be working correctly, it just iterates through and builds the div regardless of whether the name is undefined or not.

Any help would be much appreciated.

Answer

You are actually checking if the content of albums[i] equals the string undefined. You should check if the content of albums[i] is undefined. You should also use the ===/!== operators. If you want to check if the variable is null you should then check if albums[i] === null or albums[i] !== null

albums[i] != "undefined" => albums[i] !== undefined

Here is you for loop :

for (var i = 0; i < albums.length; i++){
    if ((albums[i] !== undefined) && (albums[i+1].indexOf("http") !== 1)){
        $("#thumbnail").css("overflow:", "auto");
        $("#thumbnail").css("max-height:", "100px");
        $("#thumbview").append('<div id="thumbnail"><img src=' + [i+1] + ' id="coverPhoto" height="320" width="420"></a></div>');
    };
};
Comments