Atakan Akbulut
Atakan Akbulut

Reputation: 729

Select part of array javascript

I tried select and write part of arrays. But my code select char of array .

There is my source coce:

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

Upvotes: 1

Views: 107

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386540

Assuming, you want to use the taken random values with an array as result for xxx.one and xxx.two as result.

You need to use an array of arrays and use as arrays are zero based the index zero as well. This makes a random index easier to calculate, becaus a needed addition of one for the index could be omitted.

For taking the length of the array, you need no array to wrap the value in it.

This looks right in the view, but internally it calls Array#toString method and returns a joined string, which is just the value (as string) for a single item.

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

Upvotes: 1

Related Questions