JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Useful Array Methods

bobcat
bobcat
11,623 Points

I got uppers, downers....

Not sure why I cant get my indexOf( search ) method to run?

var inStock = ['ketamine','valium','uppers','downers','weed','hash','whiskey','meth'];

var search;

function print(message){
  document.write('<p> ' + message + '</p>');
}

while ( true ){
search = prompt("Yo man, you need suttin\'? I got uppers, downers you name it. I can give you a full 'list' or you can just 'leave' "); 
    search = search.toLowerCase();
    if ( search === 'leave' ){
      break;
    } else if ( search === 'list' ){
      print( inStock.join(', ') );
    } else {
      if ( search === inStock.indexOf( search ) > -1 ){
        print('Yeah man, I got plenty of ' + search );
    } else {
        print('No man, I aint got no ' + search ); 
    }
  }
}

2 Answers

var inStock = ['ketamine','valium','uppers','downers','weed','hash','whiskey','meth'];

var search;

function print(message){
  document.write('<p> ' + message + '</p>');
}

while ( true ) {
search = prompt("Yo man, you need suttin\'? I got uppers, downers you name it. I can give you a full 'list' or you can just 'leave' "); 
    search = search.toLowerCase();
    if ( search === 'leave' ){
      break;
    } else if ( search === 'list' ){
        print( inStock.join(', ') );
    } else {
        if (  inStock.indexOf( search ) >= 0 ){
          print('Yeah man, I got plenty of ' + search );
    } else {
        print('No man, I aint got no ' + search ); 
    }
  }
}

P.S You will see the "answers" just after you will type 'leave' because since this video recorded, Javascript updated and it can not print (document.write) through a loop.

bobcat
bobcat
11,623 Points

Hi Yuval, thanks for your quick response.

Your solution didn't help when I tried or answer why Dave's example in the video worked and mine didn't. I went back and started from scratch and now it works the same as the example in the video, so I assume I was missing a curly brace or it was a typo.

I was using Firefox so the list and responses appeared as soon as I asked in the prompt unlike chrome which waits until you break from the loop to print the answer.

Thanks anyway.