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
.
- 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 is undefined
until the line you have declared it. To help remember that, I normally put my var
declarations at the top of the function.
- Put
++i
(or i++
, or i+=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.