admin管理员组

文章数量:1395025

can anyone suggest a snippet or a short method to solve this:

array = [a,b,c,d,e,f]

currentIndex = 2;

getOffset(array,currentIndex,2); // 2+2 = 4 -> return 'e'

getOffset(array,currentIndex,-2); // -> return 'a'

getOffset(array,currentIndex,-3); // -> return 'f'

getOffset(array,currentIndex,-4); // -> return 'e'

getOffset(array,currentIndex, 5); // -> return 'b'

So if the the targetted index is bigger than array.length or < 0 -> simulate a circle loop inside the array and continue to step inside the indexes.

Can anyone help me? I tried, but got a buggy script :(

TY!

can anyone suggest a snippet or a short method to solve this:

array = [a,b,c,d,e,f]

currentIndex = 2;

getOffset(array,currentIndex,2); // 2+2 = 4 -> return 'e'

getOffset(array,currentIndex,-2); // -> return 'a'

getOffset(array,currentIndex,-3); // -> return 'f'

getOffset(array,currentIndex,-4); // -> return 'e'

getOffset(array,currentIndex, 5); // -> return 'b'

So if the the targetted index is bigger than array.length or < 0 -> simulate a circle loop inside the array and continue to step inside the indexes.

Can anyone help me? I tried, but got a buggy script :(

TY!

Share Improve this question asked Jun 22, 2012 at 9:15 zsitrozsitro 1,9043 gold badges25 silver badges34 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Try this:

function getOffset(arr,index, offset){   
    return arr[(arr.length+index+(offset%arr.length))%arr.length];
}

This should do the trick, I suppose:

function getOffset(arr,n,offset) {
   offset = offset || 0;
   var raw = (offset+n)%arr.length;
   return raw < 0 ? arr[arr.length-Math.abs(raw)] : arr[raw];
}

var arr = ["a", "b", "c", "d", "e", "f"];
getOffset(arr,-3,2); //=> 'f'
getOffset(arr,-3);   //=> 'd'
//but also ;~)
getOffset(arr,-56,2);  //=> 'a'
getOffset(arr,1024,2); //=> 'a'

Use the modulus operator:

function getOffset(arr, index, step) {
  return arr[(((index + step) % arr.length) + arr.length) % arr.length];
}

本文标签: Javascript Array get offsetindex from specific indexStack Overflow