lundi 21 novembre 2016

What's the best way to execute a code block based on the input of a user if it matches a value in an array?

I've tried two ways to achieve this, please see below:

var cat = ['travel', 'business', 'environment', 'culture', 'football', 'politics', 'world', 'commentisfree', 'lifestyle', 'fashion', 'technology', 'sport', 'money', 'science'];

var userInput = $("#mySearch").val();

for(var i=0; i < cat.length; i++){
    if (userInput == cat[i]){
        // do something
    }else{
        // do something else
    }
}

This worked, however the else condition was executed until it found the value. I then tried to lose the array with the below:

var userInput = $("#mySearch").val();

if ( userInput == 'travel' || 'business' || 'environment' || 'culture' || 'football' || 'politics' || 'world' || 'commentisfree' || 'lifestyle' || 'fashion' || 'technology' || 'sport' || 'money' || 'science' ){
    // do something
}else{
    // do something else
}

This way also works, however, it fires for values that aren't between the condition brackets (not entirely sure why??). Explanations and solutions are more than welcome! I'm new to JS

Aucun commentaire:

Enregistrer un commentaire