JavaScript prints the entire array instead of single element -
var input = document.queryselector("input"); var button = document.queryselector("button"); var inventory = ["jacket","pants","map"]; var actionsiknow = ["north","east","west","south"]; var messages = ["a group of dangerous minions. turn back, not have sword", "you have gone deep forest. want go further?", "a giant ruby crystal", "a silent lake; see reflection in water", "clear patch of land", "a sleeping dragon. bettwe not wake up", "a solitary cottage. faint music can heard inside", "looks path leads cottage of flute maker", "a lot of tombstones, looks old graveyard" ]; var userinput; var startingpos = 4; button.addeventlistener("click",takemethere,false); function takemethere(){ userinput = input.value; userinput = userinput.tolowercase(); if(userinput!=null){ validateinput(); } } function validateinput(){ for(var i=0;i<actionsiknow.length;i++){ if(userinput.indexof(actionsiknow[i]!=-1)){ move(actionsiknow[i]); } } } function move(where){ console.log(where); } i making text based exploring game user can select go. user wants go depends on entered in textfield. data passed move(where) console.log(where). instead of printing north, east, etc prints whole of actionsiknow array. why ?
simple mistake. change
if(userinput.indexof(actionsiknow[i]!=-1)){ to this:
if (userinput.indexof(actionsiknow[i]) !== -1 ) { edit. per discussion in comments. able validate input in different format east, move east, disallow easter may want make use of more sophisticated validation rules. maybe using regular expressions:
if (userinput.match(new regexp("\\b" + actionsiknow[i] + "\\b"))) { move(actionsiknow[i]); }
Comments
Post a Comment