gpt4 book ai didi

javascript - 选择数组javascript的一部分

转载 作者:行者123 更新时间:2023-11-30 20:26:10 27 4
gpt4 key购买 nike

我尝试选择并写入数组的一部分。但是我的代码选择了数组的char

这是我的源代码:

<html>
<meta charset="utf-8">

<body>
<table border = "1" >
<tr>
<th>All Arrays</th>
<th>Selected Array</th>
</tr>
<tr>
<td><p id="TotalArray"></p></td>
<td><p id="SelectedId"></p></td>
</tr>
</table>

<table border = "1" >
<tr>
<th>PartOne</th>
<th>PartTwo</th>
</tr>
<tr>
<td><p id="PartOneItem"></p></td>
<td><p id="PartTwoItem"></p></td>
</tr>
</table>



<input type="button" class="button" value="Try" onClick="TryButton();">

<script>

ArrayList = new Array();
ArrayList[1] = "one.one"+"one.two";
ArrayList[2] = "two.one"+"two.two";
ArrayList[3] = "three.one"+"three.two";
ArrayList[4] = "four.one"+"four.two";
document.getElementById("TotalArray").innerHTML = [ ArrayList.length-1];

function TryButton(){
ArrayId = Math.floor(Math.random()*3 + 1)
document.getElementById("PartOneItem").innerHTML = ArrayList[ArrayId][0];
document.getElementById("PartTwoItem").innerHTML = ArrayList[ArrayId][1];
document.getElementById("SelectedId").innerHTML = ArrayId;
}
</script>
</body>
</script>
</body>
</html>

最佳答案

假设,您希望将获取的随机值与数组一起用作 xxx.onexxx.two 的结果。

您需要使用数组的数组,并且使用数组也是基于零的索引零。这使得随机索引更容易计算,因为可以省略索引所需的添加。

为了获取数组的长度,您不需要数组来包装其中的值。

这在 View 中看起来是正确的,但在内部它调用了 Array#toString方法并返回一个连接的字符串,它只是单个项目的值(作为字符串)。

function TryButton() {
var index = Math.floor(Math.random() * list.length);
document.getElementById("PartOneItem").innerHTML = list[index][0];
document.getElementById("PartTwoItem").innerHTML = list[index][1];
document.getElementById("SelectedId").innerHTML = index;
}

var list = [
["one.one", "one.two"],
["two.one", "two.two"],
["three.one", "three.two"],
["four.one", "four.two"]
];

document.getElementById("TotalArray").innerHTML = list.length;
<table border="1">
<tr><th>All Arrays</th><th>Selected Array</th></tr>
<tr><td><p id="TotalArray"></p></td><td><p id="SelectedId"></p></td></tr>
</table>
<table border="1">
<tr><th>PartOne</th><th>PartTwo</th></tr>
<tr><td><p id="PartOneItem"></p></td><td><p id="PartTwoItem"></p></td></tr>
</table>
<input type="button" class="button" value="Try" onClick="TryButton();">

关于javascript - 选择数组javascript的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50898662/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com