Arrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for (int counter = myArray.length - 1; counter >= 0; counter--) {
Answer from user142162 on Stack OverflowArrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for (int counter = myArray.length - 1; counter >= 0; counter--) {
use myArray.length-1
for(int counter=myArray.length-1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}
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);
}
How can I loop through an array forward and then backwards and then forwards and... etc with the modulus operator?
How to iterate backwards and forwards through an array?
Looping backwards over an array - Archive - Godot Forum
Why is iterating through an array backwards faster than forwards
Videos
Say I have an array:
arr = [1,2,3,4,5]
and I want to output this using a simple counter and the modulus operator
1 2 3 4 5 4 3 2 1 2 3 4 5 ...
Is this possible? I know that you can loop through an array and start over at the beginning by doing
arr[count % len(arr)]
but how do I just switch directions instead of going back to the beginning?
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
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.
Hi! I've found my self wanting to iterate an array in reverse order. I have something like this.
const items: [256]u8 = undefined;
// initialize some items and keep the count in items_count
const items_count = 25;
var i: i16 = @intCast(i16, items_count) - 1;
while (i >= 0) : (i -= 1) {
const item =items[i];
// do something with item
}the compiler is complaining that items[i] is expecting a usize, which I totally understand, my simple solution would be to use @intCast(usize, i) an call it a day. but I wanted to know if there is some pattern I am missing or what would be the best way to acomplish this.
Thanks!
noUncheckedIndexedAccess is primarily useful for objects, and for arrays if the index you're looking up might be more than the length of the array.
If you can be absolutely certain that the value exists at the index specified - such as with dead-simple code like this (assuming you don't mutate the array inside the function) - then simply assert that the value exists before passing it around:
Copyfor (let i = arr.length - 1; i >= 0; --i) {
doSomething(arr[i]!);
}
Another option would be to reverse the array, then iterate over it, which is a bit more computationally expensive, but easier to make sense of at a glance.
Copyarr.reverse().forEach(doSomething);
Copy// no mutation:
[...arr].reverse().forEach(doSomething);
Copy// no mutation:
for (const item of [...arr].reverse()) {
doSomething(item);
}
Those last three are what I'd prefer over a for loop when feasible.
Why you didn't do it as anyone else
Copyarr.map(dosonething);
Buy if you still want to do it as you Is add an if
Copyif (art[I]!==undefined){
dosonething(art[I]);