简体   繁体   中英

Loop through array match variable and assign condition to execute

Currently I am building web app which is able to show the weather in real time but I stuck on one of my ideas. So I am using free forecast API and I am taking the Object value for ICON (icon that says in different time if it's raining, snowing and so on). I have created array with all possible options about this object value: 'icon' according the documentation of that forecast API and I have prepared all Images in my Img folder. So my idea is to loop through this array with all possible options for weather condition then if there is a match with my ICON variable which is changing all the time according to my API, I want to be able to assign the proper image for the CURRENT wheather condition: Rain - Assign Rain.png or if it is Snowing - Assign Snow.png and so on.

Here is my code until now but I have problem with the matching my array with this ICON variable output. And I have made also array with all of my images that I would like to assign if there is a match.

var weatherConditions = [
            'Clear',
            'Possible Light Precipitation',
            'Light Precipitation',
            'Precipitation',
            'Drizzle',
            'Possible Drizzle',
            'Possible Light Rain',
            'Light Rain',
            'Rain',
            'Heavy Rain',
            'Possible Light Sleet',
            'Light Sleet',
            'Sleet',
            'Heavy Sleet',
            'Possible Flurries',
            'Flurries',
            'Possible Light Snow',
            'Light Snow',
            'Snow',
            'Heavy Snow',
            'Windy',
            'Dangerously Windy',
            'Foggy',
            'Mostly Cloudy',
            'Overcast',
            'Dry and Breezy',
            'Drizzle and Dangerously Windy'
        ]; 
    var arrayLength = weatherConditions.length;
    for (var i = 0; i < arrayLength; i+=1){
        if ( weatherConditions[i].indexOf(dayOneIconTokyo) ){
            console.log('working');
        } else{
            console.log('not in the array');
        }
    }   

No need for looping:

if (~weatherConditions.indexOf(dayOneIconTokyo)) { // returns true if dayOneIconTokyo
                                                   // is in weatherConditions
    console.log('working');
} else{
    console.log('not in the array');
}

Assuming dayOneIconTokyo is an array

for (var i = 0; i < dayOneIconTokyo.length; i++){
    if ( weatherConditions.indexOf(dayOneIconTokyo[i]) ){
        console.log('working');
    } else{
        console.log('not in the array');
    }
}

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