创建一个从数组中选择单个项的函数JavaScript

时间:2016-06-16 11:11:51

标签: javascript arrays function

我有一个问题,我对JS很新。我想创建一个函数,在单击时从数组中选择项目。我已经能够创建它,但它看起来似乎没有正确的循环。它选择整个数组而不是单个项,即使我已经指定了循环的条件从[0]开始并递增1直到数组的长度......

这就是我所拥有的:

    <button onclick=PickNum()>Pick</button>
<br />
<h1 id="cal1"></h1>
<script>

    function PickNum() {
        var arnum = [ " 1 ", " 2 ", " 3 ", " 4 " ];
        var loopz;
        var wrote = "";
        for (loopz = 0; loopz < arnum.length; loopz++) {
            wrote+= arnum[loopz];
        }
        document.getElementById('cal1').innerHTML+= wrote;

        }
    document.write(typeof arnum[loopz]);
</script>

全部谢谢

2 个答案:

答案 0 :(得分:0)

您的问题并不完全清楚,但根据您的说法判断(&#34;增加1直到数组的长度......&#34;)我相信您要打印一个数组的数组每次点击:

var arnum = [ " 1 ", " 2 ", " 3 ", " 4 " ];
var loopz = 0;
function PickNum() {
    document.getElementById('cal1').innerHTML= arnum[loopz];
    if(loopz < arnum.length -1){
        loopz++; 
    } else {
        loopz = 0;
    };
}

以下是示例:https://jsfiddle.net/gerardofurtado/enj4732o/

答案 1 :(得分:0)

var index = 0;
var arnum = [" 1 ", " 2 ", " 3 ", " 4 "];

function PickNum() {

  console.log(arnum[index]);
  index++;
  if (index == arnum.length) {
    index = 0;
  }
  
}
<button onclick=PickNum()>Pick</button>

<h1 id="cal1"></h1>