简体   繁体   English

Javascript数组从特定索引获取偏移索引

[英]Javascript Array get offset-index from specific index

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. 因此,如果目标索引大于array.length或<0->在数组内部模拟一个圆环,然后继续进入索引内部。

Can anyone help me? 谁能帮我? I tried, but got a buggy script :( 我尝试过,但是有一个错误的脚本:(

TY! TY!

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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM