1

I have an array of numbers from 1 to 6. But my for loop is greater than this number. I want to make my array turn back to 1 when loop's max number is equal. So basically if max number is 10 it should count as 1,2,3,4,5,6,1,2,3,4.

var myFiles =  new Array(1,2,3,4,5,6);
var filecount = myFiles.length;
var layercount = 10;
var f = 0;
var n = 0;

for(var m = 0; m < layercount; m++,n++) { 
    if (m > f) { 
        f = 0; 
        n = n - m; 
        f = f + n;
    }
    $.write (myFiles[f]);    
}

2 Answers 2

1

You could use the remainder operator % with the length of the array for the index of the array.

var array = [1, 2, 3, 4, 5, 6],
    i,
    l = 10;
    
for (i = 0; i < l; i++) {
    console.log(array[i % array.length]);
}

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much @yajiv and NinaScholz
0

Use %

var myFiles =  new Array(1,2,3,4,5,6);
var filecount = myFiles.length;
var layercount = 10;
for( var m = 0; m < layercount; m++){ 
    console.log(myFiles[m % filecount])    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.