使用 Array.prototype.reverse() 反转数组的元素

Reversing the elements of an array with Array.prototype.reverse()

我对console.log(a)的结果有点疑惑。为什么数组 "a" 中元素的顺序被颠倒了?我理解数组 "reversed," 的逻辑,但无法理解数组 "a."

发生的事情

在 Mozilla 开发者网络 (here) 上找到的示例。

var a = ['one', 'two', 'three'];
var reversed = a.reverse(); 

console.log(a);        // ['three', 'two', 'one']
console.log(reversed); // ['three', 'two', 'one']

reverse 函数将就地反转数组(它 modifies/mutate 原始数组对象):

var a = ['one', 'two', 'three'];
a.reverse();
console.log(a);        // ['three', 'two', 'one']

如果你不想改变原始数组,你可以在反转之前制作一个浅拷贝(使用 slice 函数):

var reversed = a.slice().reverse();
console.log(a);        // ['one', 'two', 'three']
console.log(reversed); // ['three', 'two', 'one']

关注description:

The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

到位是发生这种情况的原因。