简体   繁体   中英

Reverse an Array (not using reverse) - map & unshift - Javascript

I'm trying to reverse an array without using reverse and I can't work out why my code isn't working. If you could help at all that would be great thanks.

let inverse = [];
inverse = array.map( element => inverse.unshift(element) )

If you could help at all that would be great thanks.

You need no mapping, just iterating.

 const array = [1, 2, 3, 4], reverse = []; array.forEach(v => reverse.unshift(v)); console.log(reverse);

Another approach.

 const array = [1, 2, 3, 4], size = array.length, result = array.map((_, i, arr) => arr[size - i - 1]); console.log(result);

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