admin管理员组文章数量:1302352
This code is now making 1
to 4
. How can it make 4
to 1
(last to first)?
var nb = 4;
var first = ' active';
if (nb > 1) {
for (var i = 1; i <= nb; i++) {
page = page+'<span class="to-step-nb'+first+'">'+0+String(i)+'</span>';
first = '';
}
}
This code is now making 1
to 4
. How can it make 4
to 1
(last to first)?
var nb = 4;
var first = ' active';
if (nb > 1) {
for (var i = 1; i <= nb; i++) {
page = page+'<span class="to-step-nb'+first+'">'+0+String(i)+'</span>';
first = '';
}
}
Share
edited Sep 4, 2015 at 11:32
Armali
19.4k14 gold badges61 silver badges184 bronze badges
asked Sep 4, 2015 at 11:18
mamadymamady
1781 gold badge1 silver badge11 bronze badges
3
-
1
Your code is missing a
}
btw. – Andy Commented Sep 4, 2015 at 11:21 -
There are a thousand ways to loop backwards, and I'm sure you could have googled it a lot faster than the time it took to write the question, but here you go, my favorite backwards loop:
for(var i=len;i-->1;) { .. }
– Jite Commented Sep 4, 2015 at 11:23 - possible duplicate of What is the most efficient way to reverse an array in Javascript? – romuleald Commented Sep 4, 2015 at 11:29
2 Answers
Reset to default 8nb
should benumber
notstring
- You're missing
}
at the end Use the condition
for (var i = nb; i > 0; i--)
to reverse the loop.
String(i)
is not requiredfirst
is set to empty string, after first iteration, so now, you'll have last item activeif (nb > 1)
, is not required, as if the condition fails,for
will not executeYou can use Shorthand for
a = a + ..
asa += ..
Code:
var nb = 4;
var first = ' active';
for (var i = nb; i > 0; i--) {
page += '<span class="to-step-nb' + first + '">' + 0 + i + '</span>';
first = '';
}
for (var i = nb; i >= 1; i--) {
// do something
}
本文标签: javascript(JS) make forloop function go from last to firstStack Overflow
版权声明:本文标题:javascript - (JS) make for-loop function go from last to first - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741704632a2393486.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论