javascript - 如何在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>
解决方案
假设您的数组中有字符串,您可以只使用索引和偏移量来获取给定随机索引的左右值。
不在数组中的索引值显示为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');
推荐阅读
- google-cloud-dataflow - 使用 Composer 和数据流的 ETL 管道设计决策
- javascript - 如果不可用,如何隐藏下拉选项?
- c# - 如何更改滑块上拇指的 ZIndex
- android - 使用 MutableLiveData 对 View Model 方法进行 Android Mockito 测试
- django - fields.E305 反向查询名称与反向查询名称冲突
- sql - Sql/eloquent 按最低价格排序有很多字段
- substrate - 启动链时添加 PoA 权限
- networkx - 从具有任何选定节点的大型 Networkx 图中提取子图?
- java - 无法以崇高的文本运行程序:[在 x 秒内完成]
- html - 如果表单值与值匹配,则启用按钮