有没有办法在javascript上以相反的顺序在数组上使用map()?

Rob*_*use 62 javascript arrays

我想map()在javascript数组上使用该函数,但我希望它以相反的顺序运行.

原因是,我在Meteor项目中渲染堆叠的React组件,并希望顶层元素首先渲染,而其余元素在下面加载.

var myArray = ['a', 'b', 'c', 'd', 'e'];
myArray.map(function (el, index, coll) {
    console.log(el + " ")
});
Run Code Online (Sandbox Code Playgroud)

打印出来,a b c d e但我希望有一个打印的mapReverse()e d c b a

有什么建议?

Ada*_*r86 101

如果您不想反转原始数组,可以对其进行浅层复制,然后反转数组的映射,

myArray.slice(0).reverse().map(function(...
Run Code Online (Sandbox Code Playgroud)

  • @FahdLihidheb `reverse()` 确实修改了原始数组。 (13认同)
  • 我最终只是使用负索引来指定 z 索引,但从我提出问题的方式来看,这是最正确的。 (3认同)
  • 为什么我们需要 .slice(0) ?为什么不是 myArray.reverse() 而不是 myArray.slice(0).reverse() ?看起来我的评论的答案在这里:/sf/ask/351685981/ (3认同)

Ali*_*aza 13

.slice(0).reverse()你只需要在之前添加.map()

students.slice(0).reverse().map(e => e.id)
Run Code Online (Sandbox Code Playgroud)


gue*_*314 12

您可以使用 Array.prototype.reduceRight()

var myArray = ["a", "b", "c", "d", "e"];
var res = myArray.reduceRight(function (arr, last, index, coll) {
    console.log(last, index);
    return (arr = arr.concat(last))
}, []);
console.log(res, myArray)
Run Code Online (Sandbox Code Playgroud)


Har*_*rry 12

带命名回调函数

const items = [1, 2, 3]; 
const reversedItems = items.map(function iterateItems(item) {
  return item; // or any logic you want to perform
}).reverse();
Run Code Online (Sandbox Code Playgroud)

简写(没有命名回调函数)——箭头语法,ES6

const items = [1, 2, 3];
const reversedItems = items.map(item => item).reverse();
Run Code Online (Sandbox Code Playgroud)

这是结果

在此处输入图片说明


tyb*_*org 10

根本不改变数组,这是我想出的一线O(n)解决方案:

myArray.map((val, index) => myArray[myArray.length - 1 - index]);
Run Code Online (Sandbox Code Playgroud)


Mad*_*deo 8

另一种解决方案可能是:

const reverseArray = (arr) => arr.map((_, idx, arr) => arr[arr.length - 1 - idx ]);
Run Code Online (Sandbox Code Playgroud)

您基本上使用数组索引

  • 这似乎是一种奇怪的方法,但是如果您想访问除元素之外的索引,而不是真的想执行 reduce 等,那么 reduceRight 方法也很奇怪。在我的情况下,这是最干净的解决方案。 (2认同)

edi*_*999 7

我更喜欢写一次 mapReverse 函数,然后使用它。此外,这不需要复制数组。

function mapReverse(array, fn) {
    return array.reduceRight(function (result, el) {
        result.push(fn(el));
        return result;
    }, []);
}

console.log(mapReverse([1, 2, 3], function (i) { return i; }))
// [ 3, 2, 1 ]
console.log(mapReverse([1, 2, 3], function (i) { return i * 2; }))
// [ 6, 4, 2 ]
Run Code Online (Sandbox Code Playgroud)


小智 7

通过使用传播语法,您可以使数组比Array.prototype.mapArray.prototype.slice更容易反转。

例如:

{
  const myArray = ['a', 'b', 'c', 'd', 'e'];
  [...myArray].reverse().map(el => console.log(el + " ")); 
}
Run Code Online (Sandbox Code Playgroud)