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 badges3 Answers
Reset to default 5Try 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
版权声明:本文标题:Javascript Array get offset-index from specific index - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744107670a2591140.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论