[英]for/in loop decrement javascript
I am trying to decrement a for/in loop in js. 我正在尝试减少js中的for / in循环。
I have found lots of instruction on decrementing a for-loop, but had no luck finding a statement that decrements a for/in loop. 我发现了很多关于减少for循环的指令,但是没有运气找到减少for / in循环的语句。
var classRegister = ["Lawrence", "John", "Jeff", "Bobbi"]; for( var index in classRegister ) { console.log(classRegister[index]); }
This is my incrementing for/in loop statement that I want to modify to decrement. 这是我要修改为递减的for / in循环增量语句。
Use basic for
loop & avoid for..in
to iterate an array 使用基本的
for
循环并避免for..in
迭代数组
var classRegister = ["Lawrence", "John", "Jeff", "Bobbi"]; for (let i = classRegister.length - 1; i >= 0; i--) { console.log(classRegister[i]); }
If you want to use for/in you can, you simply need to subtract your index from the last index value. 如果您想使用/输入,则只需从上一个索引值中减去索引即可。
var classRegister = ["Lawrence", "John", "Jeff", "Bobbi"];
for( var index in classRegister ) {
console.log(classRegister[classRegister.length - 1 - index]);
}
You should not use for..in for arrays instead use simple loop 您不应该将for..in用于数组,而应使用简单循环
var classRegister = ["Lawrence", "John", "Jeff", "Bobbi"]; for(let index = classRegister.length-1; index >= 0; index-- ) { console.log(classRegister[index]); }
Or a while loop 或一会儿循环
var classRegister = ["Lawrence", "John", "Jeff", "Bobbi"]; let index = classRegister.length-1; while(index >= 0) { console.log(classRegister[index]); index--; }
There are hacky ways to do but you should never use them IMO 有一些骇人听闻的方法可以做,但您绝对不要使用它们
var classRegister = ["Lawrence", "John", "Jeff", "Bobbi"]; let copy = [...classRegister].reverse() // this reverse array in place for( var index in copy ) { console.log(copy[index]); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.