How to put the k var in the for-loop construction. I want more pact code, not like this one:
var k = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] == 'x') {
k++;
}
}
How to put the k var in the for-loop construction. I want more pact code, not like this one:
var k = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] == 'x') {
k++;
}
}
Share
Improve this question
edited Jul 21, 2010 at 21:28
Yacoby
55.5k16 gold badges117 silver badges121 bronze badges
asked Jul 21, 2010 at 21:25
anonanon
212 bronze badges
0
6 Answers
Reset to default 3Although not as efficient due to the fact that a new array is constructed, using filter leads to far more pact code.
arr.filter(function(e){ return e == 'x'; }).length;
An alternative, although far less clear avoids constructing a new array:
arr.reduce(function(x, e){ return x + (e == 'x' ? 1 : 0); }, 0);
Add it to the first clause in the for statement, separated by a ma:
for (var i = 0, k = 0; i < mystick.length; i++) {
if (mystick[i] == 'huge') {
k++;
}
}
Not so readable, but seems to work:
for (var i = 0, k = 0; i < mystick.length; i++) {
mystick[i] == "huge" && k++;
}
Here's a single liner (even uglier):
for (var i = k = 0; i < mystick.length; i++, mystick[i] == "huge" && k++);
Because this is javascript and javascript doesn't have block scope, it is actually best practice to do the opposite - declare both i
and k
outside the body of the for
loop, at the top of the function or script block. This way you don't trick yourself into thinking i
is restricted to the for
loop. You could still initialize both in the body of the for
loop, as others suggest:
var k,
i;
...
for (i = 0, k = 0; i < arr.length; i++) {
if (arr[i] == 'x') {
k++;
}
}
You should also measure the length of the stick in the first part of the for loop, otherwise you'll be measuring it with every iteration. And you can also make the k
bit even more pact:
for (var i = k = 0, j = mystick.length; i < j; i++) {
if (mystick[i] == 'huge') {
k++;
}
}
Just to keep things interesting, how about a pletely different (and slightly faster since decrementing while loops tend to perform a little better in javascript) method.
var i = arr.length;
while(i--){
if(arr[i] == 'x')k++;
}