我有一个数组和方向变量,例如:
var fruits = ["apple","banana","cherry"];
var direction = 1;
//1 => forward; -1 => backwards;
然后打电话给我,我可能会说
index = **SOME MATHS HERE**
var fruit = fruits[index]
因此,目标是建立一个可以在数组中前后循环的循环。我想要一个迭代遍历数组的for循环。我知道我可以使用if循环说这样做
if(direction < 0){//backwards}
类似的东西,但这意味着两个代码,当我可以使用一个聪明的数学运算来迭代它。
答案 0 :(得分:4)
这样的事情会起作用:
var fruits = ["apple","banana","cherry"];
var direction = 1; // or -1
var i = direction > 0 ? 0 : fruits.length - 1,
stop = direction > 0 ? fruits.length : -1;
for (; i != stop; i += direction)
console.log(i, fruits[i]);
var fruits = ["apple", "banana", "cherry"];
function iterate(direction) {
var results = $("#results").empty();
var i = direction > 0 ? 0 : fruits.length - 1,
stop = direction > 0 ? fruits.length : -1;
for (; i != stop; i += direction)
$("<span>").text(i + ": " + fruits[i] + "\n").appendTo(results);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button onclick="iterate(1)">Forward</button>
<button onclick="iterate(-1)">Backward</button>
<pre id="results" />
&#13;
答案 1 :(得分:2)
做一个功能。
var fruits = ["apple","banana","cherry"];
var direction = 1;
function iterate(arr, direction, callback){
if(direction === 1){
console.log("Forwards");
for(var i = 0; i < arr.length; i++){
//Iterate through array regularly
if(callback !== undefined){
callback(arr[i]);
}
}
}
else{
console.log("Backwards");
for(var i = arr.length - 1; i >= 0; i--){
//Iterate through array backwards
if(callback !== undefined){
callback(arr[i]);
}
}
}
}
iterate(fruits, direction, function(a){
console.log(a);
});
iterate(fruits, -direction, function(a){
console.log(a);
});
请参阅此jsfiddle
答案 2 :(得分:0)
请参阅http://jsfiddle.net/ZfL24/1/
var fruits = ["apple","banana","cherry"];
var direction = 1;
for(var i = 0; i < fruits.length; i++) {
var fruit = fruits[direction === 1 ? i : fruits.length - (i + 1)];
}
答案 3 :(得分:0)
如何有条件地反转数组所以它没有那么多代码,因为你似乎想避免这样:
if (direction < 0) {
fruits.reverse();
}
然后,使用你的for循环,它将根据方向的值向后或向前移动。
答案 4 :(得分:0)
这是一个通用的&#34;双向&#34;循环:
function bdLoop (step, amount[, additional arguments]) {
var n = (step < 0) ? amount - 1 : 0,
x, xstep = Math.abs(step);
for (x = 0; x < amount; x += xstep, n += step) {
// x always equals to 0 .. amount stepped by xstep
// n equals to 0 .. amount or amount .. 0 stepped by step, depends on direction (±step)
}
return[ results];
}
在循环中,您可以引用外部作用域中的变量,处理传递的参数,还可以传递函数引用并调用传递的函数等。