Javascript - 使用 forEach 向后循环遍历数组
问题描述:
有没有一种方法可以使用 forEach
(不是任何其他类型的循环,我知道如何使用 for/标准方法)在数组中向后循环而不实际反转数组本身?
Is there a way to loop backwards through an array using forEach
(not any other kind of loop, I know how to do with with a for / standard ways) and without actually reversing the array itself?
答
let arr = [1, 2, 3];
arr.slice().reverse().forEach(x => console.log(x))
将打印:
3
2
1
arr
仍然是 [1, 2, 3]
,.slice()
创建一个浅拷贝.
arr
will still be [1, 2, 3]
, the .slice()
creates a shallow copy.