How to put the k var in the for-loop construction. I want more compact 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 compact code, not like this one:
var k = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] == 'x') {
k++;
}
}
Add it to the first clause in the for statement, separated by a comma:
for (var i = 0, k = 0; i < mystick.length; i++) {
if (mystick[i] == 'huge') {
k++;
}
}
Although not as efficient due to the fact that a new array is constructed, using filter leads to far more compact 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);
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 compact:
for (var i = k = 0, j = mystick.length; i < j; i++) {
if (mystick[i] == 'huge') {
k++;
}
}
Just to keep things interesting, how about a completely 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++;
}
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++;
}
}