显示数组JS中元素的位置

我的问题如下:如何使用i获取数组元素的位置?

  1. 我只需要使用 2 个功能。

  2. 第一个函数请求元素,调用第二个函数并显示位置。

  3. 第二个函数在数组中查找元素并返回该元素的位置。

// Simple array with 5 elements. 


var x = ["a","b","c","d","e"];


first_function();  // The call for the first function 


function first_function(){

  const result = prompt("Search the word");

  document.write(i);

  second_function();

}


function second_function(x){

  let i = 0;

  while ( i < 5 ){

    if (x[i] == result){

    return i;

    i++

  }

}


肥皂起泡泡
浏览 155回答 3
3回答

aluckdog

为什么不使用Array.prototype.indexOf()?const&nbsp;letters&nbsp;=&nbsp;["a",&nbsp;"b",&nbsp;"c",&nbsp;"d",&nbsp;"e"]; letters.indexOf(input);

慕容708150

尝试这样的事情。对您的代码进行小的更改。var x = ["a", "b", "c", "d", "e"];function first_function() {&nbsp; const result = prompt("Search the word");&nbsp; document.write(second_function(result));}function second_function(result) {&nbsp; let i = 0;&nbsp; while ( i < 5 ){&nbsp; &nbsp; if (x[i] === result){&nbsp; &nbsp; return i;&nbsp; &nbsp; }&nbsp; &nbsp; i++&nbsp; }}first_function();

温温酱

我想你的意思是:document.write(second_function(i));那么,您想问用户他们想要获取索引的字母是什么?询问用户的输入。[可选]转换字母在数组中找到字母的索引。const letters = ["a", "b", "c", "d", "e"];prompUserForIndex();function prompUserForIndex() {&nbsp; let requestedLetter = prompt("Search the word").trim().toLowerCase();&nbsp; document.write(`Index: ${findIndex(letters, requestedLetter)}`);}function findIndex(letters, letter) {&nbsp; return letters.indexOf(letter);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript