let arr = [1, 2, 3];
arr.slice().reverse().forEach(x => console.log(x))
will print:
3
2
1
arr will still be [1, 2, 3], the .slice() creates a shallow copy.
let arr = [1, 2, 3];
arr.slice().reverse().forEach(x => console.log(x))
will print:
3
2
1
arr will still be [1, 2, 3], the .slice() creates a shallow copy.
Just use a for loop. Start at the end of the array and go backwards from there.
const array = ['blastoff', 1, 2, 3];
for (let index = array.length - 1; index >= 0; index--) {
const element = array[index];
console.log(element);
}
Hi, I've got a modal I've made on a site but I would like to have a functional image gallery that goes back and forth though a list of local images no matter that size of the array. My problem is I have the modal, images and button events set but the function messes up as it get to the end of the array of images or the start or when i'm moving forward/backwards then press the reverse as I have to pres the button twice for it to work .
I'd post the code but it's so messed up I'd rather know the best clean solution for this issue.
so
-
I need the list of images thats in the array to loop as it get to the end/start of the list (using a previous and next button).
1a. As it get to the end of the list. 1b. As it get to the start needed to go back to the end.
I've delayed coding for a while as its frustrated me please help :/
javascript - How do i loop through an array backwards? - Stack Overflow
javascript - Why is iterating through an array backwards faster than forwards - Stack Overflow
For loop backwards
javascript - How to iterate backwards and forwards through an array? - Stack Overflow
Videos
Simple, loop the other way. Instead of i++ use i--:
for(i = 0; i < array.length; i++){
// do something with array[i]
}
// you go backwards:
for(i = array.length - 1; i >= 0; i--){
// do something with array[i]
}
Option 1
var arr = [1, 2, 3, 4, 5];
for (var i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]);
}
Option 2
var arr = [1, 2, 3, 4, 5];
arr.slice().reverse().forEach((item) => {
console.log(item);
});
Because your forwards-condition has to receive the length property of your array each time, whilst the other condition only has to check for "greater then zero", a very fast task.
When your array length doesn't change during the loop, and you really look at ns-perfomance, you can use
for (var i=0, l=arr.length; i<l; i++)
BTW: Instead of for (var i = arr.length; i > 0; --i) you might use for (var i = arr.length; i-- > 0; ) which really runs through your array from n-1 to 0, not from n to 1.
Because in the first form you are accessing the property length of the array arr once for every iteration, whereas in the second you only do it once.
Something like this would work:
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);
}
<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" />
Just make a function.
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);
});
See this jsfiddle
Almost. You have to:
- Decrease
iinstead of increasing it, and - Start from
array.length-1, because array indexes start from 0, not 1.
So use instead:
for (let i = array.length-1; i >=0 ; i--) {
It occurs cause arrays in Javascirpt are not limited to the size that they were declared. So, it implies that if you try to access an empty position you will receive undefined. For example, in this case, if you do array[5] you will receive undefined and not a ArrayIndexOutOfBoundsException as it would happen in Java.
Also, you should take a look in your code. Since you're iterating the array backwards, you sohuld decrement i with i-- instead of incrementing it.
You don't need to slice the array (which uses additional memory, as it creates a new array) to do that.
What you are describing is a loop that starts at index = 96 until it reaches 0, decreasing index one by one.
So you just need to change let i = keyToValue2.length[96] - 1 to let i = 96.
Here's an example using an array with 32 values and logging them backwards, starting at index 16. Just used these values because StackOverflow snippets limit the number of log entries:
// This creates a new array with 32 numbers (0 to 31, both included):
const array = new Array(32).fill(null).map((_, i) => `Element at index ${ i }.`);
// We start iterating at index 16 and go backwards until 0 (both included):
for (let i = 16; i >= 0; --i) {
console.log(array[i])
}
If you want to make sure the index 96 actually exists in your array, then use let i = Math.min(96, keyToValue2.length - 1:
// This creates a new array with 32 numbers (0 to 31, both included):
const array = new Array(32).fill(null).map((_, i) => `Element at index ${ i }.`);
// We start iterating at index 31 (as this array doesn't have 64 elements, it has only 32)
// and go backwards until 0 (both included):
for (let i = Math.min(64, array.length - 1); i >= 0; --i) {
console.log(array[i])
}
Try this,
slice array up to which index you want, then loop it reverse order.
var sliced = keyToValue2.slice(0, 96);
for (let i = sliced.length - 1; i >= 0; i--) {
console.log(keyToValue2[i])
}