I have an array ["#page1", "yield", "yield", "yield", "#page2", "yield", "#page3" ]
I want to iterate through the array top-down, starting at the last yield
and looking for the next occurence of an element not being yield
(which is #page2
).
This is what I have:
var longest = ["#page1", "yield", "yield", "yield", "#page2", "yield", "#page3" ],
longestLen = longest.length;
for (i = longestLen-2; i>=0; i--) {
if ( longest[i] != "yield") {
var gotoPage = longest[i];
}
}
I'm starting at i=5 (6 iterations) and checking if the element is not yield
. However, the current way runs through all 6 iterations, so I end up with the page#1
instead of the #page2
. I don't know how I can stop the iterations.
Using return
did not work, what other means are there? Is lastIndexOf
something I could use?
Thanks for help!
Just because noone mentioned it so far, you can also go with ES5 .some()
for that.
Looks like:
var longest = ["#page1", "yield", "yield", "yield", "#page2", "yield", "#page3" ],
gotoPage;
longest.reverse().slice(1).some(function( elem ) {
return (gotoPage = elem) !== "yield";
});
alert('goto page: ' + gotoPage);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With