简体   繁体   English

JavaScript Array unshift() 以不可变的方式

[英]JavaScript Array unshift() in an immutable way

How would you implement something like the Array unshift() method so that it creates a new array?你将如何实现类似于 Array unshift() 方法的东西,以便它创建一个新数组? Basically something like the Array concat() method but instead of placing the new item at the end, place it in the beginning.基本上类似于 Array concat() 方法,但不是将新项目放在末尾,而是将其放在开头。

You can actually accomplish this using the .concat method if you call it on an array of elements you want to put at the front of the new array.如果您在要放在新数组前面的元素数组上调用它,则实际上可以使用.concat方法完成此操作。

Working Example:工作示例:

 var a = [1, 2, 3]; var b = [0].concat(a); console.log(a); console.log(b);

Alternately, in ECMAScript 6 you can use the spread operator .或者,在 ECMAScript 6 中,您可以使用扩展运算符

Working Example (requires modern browser):工作示例(需要现代浏览器):

 var a = [1, 2, 3] var b = [0, ...a]; console.log(a); console.log(b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM