admin管理员组文章数量:1327297
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++;
}
本文标签: javascriptconstructing more complex forloopsStack Overflow
版权声明:本文标题:javascript - constructing more complex for-loops - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742205308a2432706.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论