简体   繁体   中英

JavaScript Array unshift() in an immutable way

How would you implement something like the Array unshift() method so that it creates a new array? Basically something like the Array concat() method but instead of placing the new item at the end, place it in the beginning.

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.

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 .

Working Example (requires modern browser):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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