javascript - Check if array contains? -


write function receives array of foods , checks if contains values "pizza" , "bacon". if either of values missing, add array.

var foods1 = [ "cookies", "steak" ];  var foods2 = [ "pizza", "salad" ];  var foods3 = [ "pizza", "salad" , "bacon", "chili" ];    function addfoods(array){      if( !== 'pizza' &&  !== 'bacon'){ // if it's till here put inside if          array.push('pizza');          array.push('bacon');      }        }    addfoods(foods1);

use indexof check see if either food in array , add if not:

function addfoods(array){   if (array.indexof('pizza') === -1) array.push('pizza');   if (array.indexof('bacon') === -1) array.push('bacon'); } 

demo


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -