Read array values in a loop in JavaScript

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

    @Igor Petev, JavaScript's closures are a nice concept that you can use to solve your problem.

    Please read JavaScript's Closures - w3schools article. It's really nice and excellent.

    I have used the concept of closures to solve this problem. Please leave a comment if you don't understand my code or anything else related to this problem.

    Please have a look at the below code.

    var get3items = (function () {
    
        var index = 0;
        var myStringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
        var len = myStringArray.length
    
        return function () {
           for(var count = 0; count < 3; count += 1)
           {
               console.log(myStringArray[index]);
    
               if(index == (len - 1))
               {
                   index = 0;
               }
               else {
                   index += 1;
               }
           }
        }
    })();
    
    get3items (); // First call
    
    console.log()
    get3items (); // Second call
    
    console.log()
    get3items (); // Third call
    
    console.log()
    get3items (); // Fourth call
    
    console.log()
    get3items (); // Fifth call
    
    /*
     1
     2
     3
    
     4
     5
     6
    
     7
     8
     9
    
     10
     1
     2
    
     3
     4
     5
    */
    

提交回复
热议问题