Read array values in a loop in JavaScript

前端 未结 8 2027
执笔经年
执笔经年 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:13

    You could take a function which slices three elements and if not possible, it takes the needed first values of the array as well.

    function take3() {
        var temp = array.slice(index, index += 3)
        index %= array.length;
        console.log(temp.concat(temp.length < 3 ? array.slice(0, index) : []).join(' '));
    }
    
    var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
        index = 0;

    With a mapping of a dynamic count.

    function take(length) {
        console.log(Array.from({ length }, _ => array[++index, index %= array.length]));
    }
    
    var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
        index = -1;

提交回复
热议问题