我正在尝试创建一个只占一个字母的表单,并在数组中找到它的位置(基本上是字母表)。
我写了一些这个简单的代码:
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);
演示基本功能。但是,我不确定如何将其放入function get
并使var letter
等于表单输入中的值。
我想让它返回数组中的位置,以便我可以编写一个循环(在if / else中),它将打印输入值之后的数组中的所有值。
答案 0 :(得分:2)
答案 1 :(得分:2)
尝试:alphabet[alphabet.indexOf(letter)]
或代码alphabet[letterPosition]
关于您提到的循环:使用该值,您可以使用slice
方法为您提供alphabet
数组中剩余字符的子集(ergo:不需要)用于确定数组中元素的其余部分的循环:
var subset = alphabet.slice(indexOf([a letter]));
只是为了节省一些打字:你也可以像这样声明你的字母数组:
var alphabet 'abcdefghijklmnopqrstuvwxyz'.split('');
答案 2 :(得分:2)
不确定上下文,是否加载了页面(不涉及AJAX)?我可能过于简单了:
<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>
我喜欢javascript。
答案 3 :(得分:0)
或者你可以做到
let alphabetPosition = (text) => text.toUpperCase().replace(/[^A-Z]/g, '').split('').map(ch => ch.charCodeAt(0) - 64).join(' ');