首页 > 解决方案 > 如何在html中获取数组中固定条目的下一个条目

问题描述

假设我们有数组

[a,b,c,d,e,f,g,h]。

我想编写一个在我的数组中随机取值的函数。我已经用 JS 和 HTML 编写了这个。

我的问题是:我想要所选字母的上一个和下一个字母。

例如我们得到“e”。然后我想要一个返回“d”和“f”的函数。我怎样才能做到这一点?

我的代码如下。(我的 js.file 被命名为“nyNumber.js”)。

function GetValue() {
  var myarray = new Array("a", "b", "c", "d", "e", "f", "g", "h");

  var random = myarray[Math.floor(Math.random() * myarray.length)];
  //alert(random);
  document.getElementById("message").innerHTML = random;
}
<input type="button" id="btnSearch" value="Give me" onclick="GetValue();" />
<p id="message"></p>

<script src="myNumber.js"></script>

标签: javascripthtml

解决方案


假设您的数组中有字符串,您可以只使用索引和偏移量来获取给定随机索引的左右值。

不在数组中的索引值显示为undefined

var array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
    random = Math.floor(Math.random() * array.length),
    left = array[random - 1],
    item = array[random],
    right = array[random + 1];
    
console.log(left || 'no left value', item, right || 'no right value');


推荐阅读