如何在 JavaScript 中以循环方式访问数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17483149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access array in circular manner in JavaScript
提问by Anshul
I have an array like [A,B,C,D]
. I want to access that array within a for loop like as
我有一个像[A,B,C,D]
. 我想在 for 循环中访问该数组,如
var arr = [A,B,C,D];
var len = arr.len;
for(var i = 0;i<arr.len;i++){
0 - A,B,C
1 - B,C,D
2 - C,D,A
3 - D,A,B
}
I want to access that like in JavaScript, any ideas?
我想像在 JavaScript 中一样访问它,有什么想法吗?
回答by wwgoncalves
Answering to the main question, someone can access an array in a circular manner using modular arithmetic. That can be achieved in JavaScript with the modulus operator (%
) and a workaround.
回答主要问题,有人可以使用模算术以循环方式访问数组。这可以在 JavaScript 中使用模数运算符 ( %
) 和一种解决方法来实现。
Given an array arr
of a length n
and a value val
stored in it that will be obtained through an access index i
, the circular manner, and safer way, to access the array, disregarding the value and sign of i
, would be:
给定arr
一个长度n
和val
存储在其中的值的数组,该数组将通过访问索引获得i
,循环方式和更安全的方式访问该数组,不考虑 的值和符号i
,将是:
let val = arr[(i % n + n) % n];
This little trick is necessary -- someone can not use the modulus result straightforwardly -- because JavaScript always evaluates a modulus operation as the remainder of the division between dividend (the first operand) and divisor (the second operand) disconsidering their signs but assigning to the remainder the sign of the dividend. That behavior does not always result in the desired "wrap around" effect of the modular arithmetic and could result in a wrong access of a negative position of the array.
这个小技巧是必要的——有人不能直接使用模数结果——因为 JavaScript 总是将模数运算评估为被除数(第一个操作数)和除数(第二个操作数)之间的除法的余数,不考虑它们的符号但分配给余数是红利的符号。这种行为并不总是导致模算术的理想“环绕”效果,并可能导致对数组负位置的错误访问。
References for more information:
更多信息参考:
回答by Bergi
Try this:
试试这个:
var arr = ["A","B","C","D"];
for (var i=0, len=arr.length; i<len; i++) {
alert(arr.slice(0, 3).join(","));
arr.push(arr.shift());
}
Without mutating the array, it would be
如果不改变数组,它将是
for (var i=0, len=arr.length; i<len; i++) {
var str = arr[i];
for (var j=1; j<3; j++)
str += ","+arr[(i+j)%len]; // you could push to an array as well
alert(str);
}
// or
for (var i=0, len=arr.length; i<len; i++)
alert(arr.slice(i, i+3).concat(arr.slice(0, Math.max(i+3-len, 0)).join(","));
回答by user1948585
Simply using modulus operator you can access array in circular manner.
只需使用模数运算符,您就可以以循环方式访问数组。
var arr = ['A', 'B', 'C', 'D'];
for (var i = 0, len = arr.length; i < len; i++) {
for (var j = 0; j < 3; j++) {
console.log(arr[(i + j) % len])
}
console.log('****')
}
回答by Barmar
for (var i = 0; i < arr.length; i++) {
var subarr = [];
for (var j = 0; j < 3; j++) {
subarr.push(arr[(i+j) % arr.length]);
}
console.log(i + " - " + subarr.join(','));
}
回答by DanteTheSmith
how about this one-liner I made ?
我做的这个单衬怎么样?
var nextItem = (list.indexOf(currentItem) < list.length - 1)
? list[list.indexOf(currentItem) + 1] : list[0];
回答by allez l'OM
One line solution for "in place" circular shift:
“就地”循环移位的一行解决方案:
const arr = ["A","B","C","D"];
arr.forEach((x,i,t) => {console.log(i,t); t.push(t.shift());});
console.log("end of cycle", arr); // control: cycled back to the original
logs:
日志:
0 Array ["A", "B", "C", "D"]
1 Array ["B", "C", "D", "A"]
2 Array ["C", "D", "A", "B"]
3 Array ["D", "A", "B", "C"]
"end of cycle" Array ["A", "B", "C", "D"]
If you want only the first 3 items, use:
如果您只想要前 3 项,请使用:
arr.forEach((x,i,t) => {console.log(i,t.slice(0, 3)); t.push(t.shift());});