【问题标题】:Reversing an array of objects in Javascript [duplicate]在Javascript中反转对象数组[重复]
【发布时间】:2018-08-19 12:40:01
【问题描述】:

正如标题所说,我想在 Javascript 中反转由对象组成的数组。

例如:var x = [{"score":1},{"score":2},{"score":3}]

为此,我使用了 .reverse() 方法。

现在,假设我写了这段代码

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

我希望控制台以原始顺序显示数组,然后以相反的顺序显示。但是,它确实以相反的顺序显示了两个数组。

怎么会?

【问题讨论】:

    标签: javascript arrays object


    【解决方案1】:

    最好的方法是:

    var y = [...x].reverse();

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

    【讨论】:

    • 做什么? ...
    • 克隆一个数组并反向克隆一个@JonasWilms
    • 但是……这不是问题吗?
    • 对不起@JonasWilms,我想他想在不改变原始数组的情况下反转数组...
    • I'm expecting the console to show the array in the original order, then in a reversed order. How come? 这就是问题所在。
    【解决方案2】:

    console.log() 考虑可变对象在打印到屏幕之前是否已更改。由于您的 OUTPUT -> CHANGE -> OUTPUT 过程几乎是准同步的,因此两个输出都是相同的。您必须使用 x 的副本才能获得所需的提示。

    试试这个方法:

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

    【讨论】:

    • 如果它回答了您的问题,请不要忘记将此答案标记为解决方案。提前致谢。
    • StackOverflows 清理系统的工作是通知询问者,而不是你的 :)
    【解决方案3】:

    根据此处的 MDN:https://developer.mozilla.org/en-US/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']
    

    【讨论】:

    • 这不是问题吗?
    猜你喜欢
    • 2021-12-29
    • 1970-01-01
    • 2021-04-27
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 2016-08-26
    • 2020-02-06
    相关资源
    最近更新 更多