在Javascript中反转一个对象数组

12
如标题所述,我想在Javascript中翻转由对象组成的数组。
示例:var x = [{"score":1},{"score":2},{"score":3}] 为了实现这个目的,我使用了 .reverse() 方法。
现在,假设我写了以下代码:
console.log(x);
x.reverse();
console.log(x);

我期望控制台先展示原始顺序的数组,然后反向展示。但实际上,它展示了两个都是反向的数组。

这是为什么呢?

3个回答

44

最佳实现方式是 var y = [...x].reverse()。请查看以下示例:

var x = [{"score":1},{"score":2},{"score":3}]
var y = [...x].reverse();
console.log(x);
var y = [...x].reverse();
console.log(y);


做什么?... - Jonas Wilms
克隆一个数组并反转克隆的数组 @JonasWilms - Moein Alizadeh
但是...那不是问题吗? - Jonas Wilms
抱歉 @JonasWilms,我认为他想要在不改变原始数组的情况下反转一个数组... - Moein Alizadeh
我期望控制台按照原始顺序显示数组,然后按相反的顺序显示。这是为什么? - Jonas Wilms

10

console.log() 函数在将可变对象打印到屏幕前会考虑对象是否被更改。由于您的 输出 -> 更改 -> 输出 的过程几乎是同步的,因此两个输出结果相同。为了获得所需的提示,您需要使用 x 的副本。

可以尝试以下方法:

// copy x
y = Object.assign({}, x);
console.log(y);

x.reverse();
console.log(x);  

如果这个答案回答了你的问题,请不要忘记将其标记为解决方案。提前致谢。 - user6749601
1
这是StackOverflow清理系统的工作,通知提问者,而不是你的工作 :) - Jonas Wilms

-2
根据MDN的说明:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse 函数reverse()破坏性的 这意味着函数会改变原始数组,如果你想保存原始数组,你必须创建另一个变量,像这样:
var array1 = ['one', 'two', 'three'];
console.log('array1: ', array1);
// expected output: Array ['one', 'two', 'three']

var reversed = array1.reverse(); 
console.log('reversed: ', reversed);
// expected output: Array ['three', 'two', 'one']

/* Careful: reverse is destructive. It also changes
the original array */ 
console.log('array1: ', array1);
// expected output: Array ['three', 'two', 'one']

这不是问题吗? - Jonas Wilms

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接