Skip to content Skip to sidebar Skip to footer

Array Item Index From An Offset Number

I have the following array: var list = ['first', 'second', 'third']; Now I can obviously access the first, second and third element by their indexes, respectively 0 1 and 2. If I

Solution 1:

  1. Accessing non-existent array elements will not throw any error, but return undefined

    var list = ['first', 'second', 'third'];
    console.log(list[3]);
    // undefinedconsole.log(list[4]);
    // undefined
  2. To wrap around the array, when the index is greater than the length, then you can use the mod operator, like this

    console.log(list[3 % list.length]);
    // first
    console.log(list[4 % list.length]);
    // second

Solution 2:

i wrote an example for you here: http://jsfiddle.net/h8V9N/

Array.prototype.at = function(index) {  
     return index >= this.length ? this[0] : this[index]; 
};

// usagevar list = ['first', 'second', 'third']; 
console.log( list.at(88) );

i'm adding new method 'at' to Array object prototype.

Post a Comment for "Array Item Index From An Offset Number"