Skip to content Skip to sidebar Skip to footer

How To Get Item From Array Even If Index Is Out Of Bounds

I have an array with 8 positions: var myArray = []; myArray[0] = 'text1'; myArray[1] = 'text2'; myArray[2] = 'text3'; myArray[3] = 'text4'; myArray[4] = 'text5'; myArray[5] = 'text

Solution 1:

You could accomplish this via using the "remainder" modulo operator which handles these kinds of "wrapping" scenarios :

functiongetArrayValueWithWrapping(array, index){
     returnarray[index % array.length];
}

Solution 2:

You have to calculate the remainder of division, using % (modulos) operator.

var myArray = [];
myArray[0] = "text1";
myArray[1] = "text2";
myArray[2] = "text3";
myArray[3] = "text4";
myArray[4] = "text5";
myArray[5] = "text6";
myArray[6] = "text7";
myArray[7] = "text8";
$('button').click(function(){
  alert(myArray[$('input').val()%8]);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="number"/><button>Get Text</button>

Solution 3:

I think it would work with myArray[ index %8 ]. If you then try to call index nr. 8 the modulo returns 0. If you call nr. 9, it gets you index 1 of the array.

Hope it helped.

Solution 4:

You can use the % (modulos) operator. This will take a number and divide it by another and return the remainder. For example:

x = 9 % 8;
// x == 1

Because 8 / 9 = 8 with a remainder of 1, so this will never return a number greater than 8 but will cycle through the remainders (8 % 10 == 2, 8 % 16 == 0)

Post a Comment for "How To Get Item From Array Even If Index Is Out Of Bounds"