javascript - 选择数组javascript的一部分

标签 javascript arrays html

我尝试选择并写入数组的一部分。但是我的代码选择了数组的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/

相关文章:

javascript - kendo grid初始化后如何设置pageSizes?

java - 编写一个程序来查找整数数组中最长连续序列的长度?

python - 给定一个二维 numpy 实数数组,如何生成描述每个数字强度的图像?

php - 具有随机图像大小和响应的网格

html - 如何选择元素父子

javascript - 根据单选按钮选择显示表单字段数据

JavaScript 分页

javascript - AngularJS - ngRepeat 将所选行显示为事件状态

c# - Linq 返回字符串数组

html - Bootstrap "close"类 : Button Sometimes Pushed out of Alert by Text