3 回答

TA贡献1847条经验 获得超7个赞
为什么不使用Array.prototype.indexOf()
?
const letters = ["a", "b", "c", "d", "e"]; letters.indexOf(input);

TA贡献1831条经验 获得超4个赞
尝试这样的事情。对您的代码进行小的更改。
var x = ["a", "b", "c", "d", "e"];
function first_function() {
const result = prompt("Search the word");
document.write(second_function(result));
}
function second_function(result) {
let i = 0;
while ( i < 5 ){
if (x[i] === result){
return i;
}
i++
}
}
first_function();

TA贡献1752条经验 获得超4个赞
我想你的意思是:
document.write(second_function(i));
那么,您想问用户他们想要获取索引的字母是什么?
询问用户的输入。
[可选]转换字母
在数组中找到字母的索引。
const letters = ["a", "b", "c", "d", "e"];
prompUserForIndex();
function prompUserForIndex() {
let requestedLetter = prompt("Search the word").trim().toLowerCase();
document.write(`Index: ${findIndex(letters, requestedLetter)}`);
}
function findIndex(letters, letter) {
return letters.indexOf(letter);
}
添加回答
举报