I was wondering if it's possible to state 2 statements as a FOR loop's condition in JavaScript.
for (var i = 0; i < x.length || 10; i++) {
}
instead of writing
for (var i = 0; i < x.length; i++) {
if(i<10) {
}
}
Used references (didn't help too much):
-
Visit this link w3schools.com/js/js_loop_for.aspChoxx– Choxx2015年04月03日 12:50:40 +00:00Commented Apr 3, 2015 at 12:50
-
@choxx I know how FOR works, I was just wondering if it's possible to do it in the way I asked.Kiss Koppány– Kiss Koppány2015年04月03日 12:53:30 +00:00Commented Apr 3, 2015 at 12:53
-
GUYS, the question wasnt about how a for loop works.. please keep in mind when downvoting.Kiss Koppány– Kiss Koppány2015年04月03日 12:54:59 +00:00Commented Apr 3, 2015 at 12:54
-
Well then you must also know the code you wrote in Ist part doesn't make any sense..Choxx– Choxx2015年04月03日 13:56:16 +00:00Commented Apr 3, 2015 at 13:56
-
You can't directly write i < x.length || 10; If you are assigning multiple conditions in FOR, then you must have to follow the coding rules as per standard. i < x.length || i < 10;Choxx– Choxx2015年04月03日 13:58:55 +00:00Commented Apr 3, 2015 at 13:58
2 Answers 2
If the goal is to end the loop when i reaches 10 or i reaches the end of the array, you may write it like this :
for (var i=0; i<x.length && i<10; i++) {
In that case you might also compose it like this
for (var i=0; i<Math.min(x.length,10); i++) {
or for better performances :
for (var i=0, n=Math.min(x.length,10); i<n; i++) {
7 Comments
&&. Otherwise, if x.length is smaller than 10 you'll go out of bounds.for (var i=0; i<Math.min(x.length,10); i++) { Nice and clear.The problem is not in the syntax of the for loop but in the way you put the conditional stetement:
i < x.length || 10
evaluates as
(i < x.length) || 10
that evaluates as
true || 10
or
false || 10
depending on the value of i and the length of x
The first will then result in true while the latter in 10.
So the for loop goes on forever and is not equivalent to the second code snipped you posted.
The above is to explain why the two code snippets you posted are not functionally equivalent.
The correct statement is
for (var i=0; i<x.length && i<10; i++) {
or one of the other proposed in dystroy's excellent answer.