Loop through an array at specified intervals

Let's say you have a simple array, for example

var someArray = ["1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9"];

Quoting through an array like this

for (var i = 0; i < someArray.length; i++) {
        console.log(someArray[i]);
    };

gives it in the console ......

1,2,3,4,5,6,7,8,9

.... but is there a way to iterate through an array to select only the nth elements? For example, the 3rd value would be provided in the console

1, 4, 7, ........
+4
source share
2 answers

Of course.

Your for iterator actually consists of three parts. Declaration, condition and increment.

Increment is the third parameter, and most likely you have always seen it as me ++, but it can be anything. In your example, you want to increase i by 3, so i + = 3.

for (var i = 0; i < someArray.length; i += 3) {
    console.log(someArray[i]);
};
+8
source

modulo. , , i:

var someArray = ["1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9"];

for (var i = 0; i < someArray.length; i++) {
    if( i % 3 === 0 ){
         console.log(someArray[i]);
    }
}

, , n- . 3 , n- .

+1

Source: https://habr.com/ru/post/1628037/


All Articles