为了账号安全,请及时绑定邮箱和手机立即绑定

显示数组JS中元素的位置

显示数组JS中元素的位置

肥皂起泡泡 2022-05-26 16:56:31
我的问题如下:如何使用i获取数组元素的位置?我只需要使用 2 个功能。第一个函数请求元素,调用第二个函数并显示位置。第二个函数在数组中查找元素并返回该元素的位置。// 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++  }}
查看完整描述

3 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

为什么不使用Array.prototype.indexOf()

const letters = ["a", "b", "c", "d", "e"];
letters.indexOf(input);


查看完整回答
反对 回复 2022-05-26
?
慕容708150

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();


查看完整回答
反对 回复 2022-05-26
?
温温酱

TA贡献1752条经验 获得超4个赞

我想你的意思是:

document.write(second_function(i));

那么,您想问用户他们想要获取索引的字母是什么?

  1. 询问用户的输入。

  2. [可选]转换字母

  3. 在数组中找到字母的索引。

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);

}


查看完整回答
反对 回复 2022-05-26
  • 3 回答
  • 0 关注
  • 154 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号