Read array values in a loop in JavaScript

前端 未结 8 2024
执笔经年
执笔经年 2021-02-14 06:49

I have an array in JavaScript that have defined these values:

var myStringArray = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\"];
8条回答
  •  隐瞒了意图╮
    2021-02-14 07:11

    Your variable i is local to the for loop which means it basically resets every time the loop is started. So first make your variable i global.

    var i=0;
    function employeeNames(){
        var empList =  ["1","2","3","4","5","6","7","8","9","10"];
        var output = [];
        var j=0;
        while(j<3)
        {
            output.push(empList[i])
            i=(i+1)%empList.length;
            j++;
        }
        return output;
    }
    
    console.log(employeeNames());
    console.log(employeeNames());
    console.log(employeeNames());
    console.log(employeeNames());
    console.log(employeeNames());

提交回复
热议问题