I have a for loop which goes through an array but I am trying to restrict it to break after the 2nd item.
var x="",i=0;
for (var x in marking;i=0;i++) {
if (i==2){
break;
}
index.push(marking[x]);
};
The console log error
SyntaxError: missing ) after for-loop control
for (var x in marking;i=0;i++) {
Could someone please show me how to combine the
for (var x in marking)
and
for (i=0;i<10;i++)
4 Answers 4
If you need to break after 2nd item, have you considered following approach:
for (var i=0;i<2;i++) {
index.push(marking[i]);
};
1 Comment
x
doesn't exist in your example.Simply put the i++
inside your for in loop
var i=0;
for (var x in marking) {
if (i==2){
break;
}
index.push(marking[x]);
i++;
};
NB: You don't need to declare the x
variable before the loop since you re-declare it inside of it.
2 Comments
for (... in ...)
to iterate over an Array: stackoverflow.com/questions/500504/… for in
loops for Arrays as long as you don't mess up with the array prototype or change it on the fly. The link in your comment says the same.edit
Come to think of it, you don't need a loop to do this at all. You can just take a slice
.
If index
already contains something, you can use concat
:
index.concat(marking.slice(0,2));
If index
has been declared already but is empty:
index = marking.slice(0,2);
This will add the first two items of marking
to the end of index
.
previous answer - potentially unsafe
- There's no need to have
var
x in both places. In JavaScript, a declaration anywhere within a function means that the variable exists from the top of the function but isundefined
until the line you have declared it. To help remember that, I normally put myvar
declarations at the top of the function. - Put
++i
(ori++
, ori+=1
) in your loop. (削除) Use===
when comparing two things of the same type. (削除ここまで)==
is slightly faster.
Like this:
var x,i=0;
for (x in marking) {
if (i == 2){
break;
}
index.push(marking[x]);
++i;
}
For conciseness you could even combine the increment and comparison, like:
var x,i=0;
for (x in marking) {
index.push(marking[x]);
if (++i == 2){
break;
}
}
Will break after the second item and only go through two iterations of the loop, rather than break
ing on the third.
2 Comments
==
than ===
. In this case you know i
is an integer so it's safe to use the ==
. (Source: jsperf.com/double-vs-triple)for (... in ...)
to iterate over an Array: stackoverflow.com/questions/500504/… var i=0;
for (var x in marking) {
if (i==2){
break;
}
index.push(marking[x]);
i++;
};
1 Comment
for (... in ...)
to iterate over an Array: stackoverflow.com/questions/500504/…