I am trying to create a form that takes only a single letter and finds its position in an array (which is essentially the alphabet).
I wrote some this simple code:
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var letter = "h";
var letterPosition = alphabet.indexOf(letter);
document.write(letterPosition);
to demonstrate the basic function. However, I am not sure how to put this into a function get and make the var letter equal to the value in the form’s input.
I want this to return the location in the array so that I can write a loop (inside an if/else)that will print all values in the array that come after the input value.
Try:
alphabet[alphabet.indexOf(letter)]or in your codealphabet[letterPosition]Concerning the loop you mentioned: with that value you can use the
slicemethod to give you a subset of remaining characters from thealphabetarray (ergo: no need for a loop to determine the remainder of elements from your array):And just to save you some typing: you could also declare your alphabet array like this: