Form to find value's position in a javascript array
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开发者_JAVA百科 the input value.
Try: alphabet[alphabet.indexOf(letter)]
or in your code alphabet[letterPosition]
Concerning the loop you mentioned: with that value you can use the slice
method to give you a subset of remaining characters from the alphabet
array (ergo: no need for a loop to determine the remainder of elements from your array):
var subset = alphabet.slice(indexOf([a letter]));
And just to save you some typing: you could also declare your alphabet array like this:
var alphabet 'abcdefghijklmnopqrstuvwxyz'.split('');
Build a demo http://jsbin.com/ijuco4
Not sure of the context, is this loading with the page (no AJAX involved)? I may be oversimplifying:
<input type="text" id="whichLetter" />
<script type="text/javascript">
function getLetterPosition(allLetters, letter)
{
return allLetters.indexOf(letter);
}
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 = document.getElementById("whichLetter").value;
var letterPosition = getLetterPosition(alphabet, letter);
</script>
i love javascript.
or you could do
let alphabetPosition = (text) => text.toUpperCase().replace(/[^A-Z]/g, '').split('').map(ch => ch.charCodeAt(0) - 64).join(' ');
精彩评论