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)
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)
另一种解决方案可能是:
const reverseArray = (arr) => arr.map((_, idx, arr) => arr[arr.length - 1 - idx ]);
Run Code Online (Sandbox Code Playgroud)
您基本上使用数组索引
我更喜欢写一次 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.map和Array.prototype.slice更容易反转。
例如:
{
const myArray = ['a', 'b', 'c', 'd', 'e'];
[...myArray].reverse().map(el => console.log(el + " "));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43609 次 |
| 最近记录: |