在 Javascript 中反转数组而不改变原始数组 [英] Reverse array in Javascript without mutating original array
本文介绍了在 Javascript 中反转数组而不改变原始数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Array.prototype.reverse
原地反转数组的内容(带有突变)...
Array.prototype.reverse
reverses the contents of an array in place (with mutation)...
是否有类似的简单策略来反转数组而不改变原始数组的内容(没有突变)?
Is there a similarly simple strategy for reversing an array without altering the contents of the original array (without mutation)?
推荐答案
您可以使用 slice() 复制然后 reverse() 它
You can use slice() to make a copy then reverse() it
var newarray = array.slice().reverse();
var array = ['a', 'b', 'c', 'd', 'e'];
var newarray = array.slice().reverse();
console.log('a', array);
console.log('na', newarray);
这篇关于在 Javascript 中反转数组而不改变原始数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文