假设我有一个数组var a = [1,2,3,4]
,现在我想从背面打印这个数组,比如4,3,2, 1
我知道我们可以通过这个实现
for(let i=a.length; i>= 0; i--) {
console.log(a[i])
// output is
// 4
// 3
// 2
// 1
}
但我想在增量循环的帮助下打印出类似4,3,2,1
的输出
for(let i=0; i < a.length; i++){
console.log(a[i])
// output should be
// 4
// 3
// 2
// 1
}
最佳答案
您只需获取长度并减去实际的循环值,即基于零的方法。
var a = [1, 2, 3, 4];
for (let i = 0; i < a.length; i++) {
console.log(a[a.length - 1 - i]);
}
关于javascript - 如何在增量循环中从背面打印数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53564235/