简体   繁体   English

如何显示从最后一项到第一项的数组项?

[英]How to display items of array from last to first item?

I have an array with items.我有一个包含项目的数组。 I want to render all items in reverse, without changing the order of the array.我想反向渲染所有项目,而不改变数组的顺序。

var array = [2,5,3,5,8,4,1];
array.map(item => {
return(<div>{item}</div>)    
})

//this will display: 2 5 3 5 8 4 1  
//but i want to display: 1 4 8 5 3 5 2

To be clear, I dont want to reverse the actual array because I need to be able to add new values into the array.需要明确的是,我不想反转实际数组,因为我需要能够将新值添加到数组中。 All I want is to map the array in reverse.我想要的只是 map 阵列反向。

You can do this method before you map...您可以在 map 之前执行此方法...

let reverse = [...arr].reverse()

or even better...甚至更好...

[...array].reverse().map(item => {
    return(<div>{item}</div>)    
})

You can try a solution without explicitly using reverse :您可以在不明确使用reverse的情况下尝试解决方案:

 var array = [2,5,3,5,8,4,1]; var arrayOutput = array.map((valye, index, inputArray) => inputArray[(inputArray.length - 1) - index]); console.log(arrayOutput);

But, for a better understanding of basic loop mechanics, you can try the following constructions:但是,为了更好地理解基本循环机制,您可以尝试以下构造:

 /* your array */ var array = [2, 5, 3, 5, 8, 4, 1]; /* loop forward from 2 to 1, * when 'l = array.length' is number of array elements */ for (let i = 0, l = array.length; i < l; i++) { console.log(array[i]); }

 /* your array */ var array = [2, 5, 3, 5, 8, 4, 1]; /* loop backward from 1 to 2, * when 'array.length-1' is last element of array */ for (let i = array.length - 1; i >= 0; i--) { console.log(array[i]); }

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

相关问题 如何在 html 中显示 javascript 数组中的所有项目,除了最后一项外,它们之间用逗号分隔 - How to display all items from a javascript array in html with commas in between them except the last item 显示数组的最后一项 - Display the last item of an array 从项目数组中删除一个项目只会删除最后一个项目 - Removing an item from an array of items only removes the last item CoffeeScript中的数组解构(从数组中获取第一项和最后一项) - Array destructuration in CoffeeScript (fetch first and last items from an Array) 将数组中的第一项移动到最后 - Move first item in array to be last 显示数组的最后 3 项 - Display last 3 items of the array in <tbody> 将数组的第一项和最后一项以及每个项之间的项数组分配给单独的变量的可能方法是什么? - What are possible ways of assigning an array's first and last item as well as the array of items in between each to a separate variable? 如果empty = true,则从双嵌套数组中删除第一项和最后一项 - Removing first and last item from double nested array if empty = true AngularJS / JavaScript Splice-总是从数组中删除第一个或最后一个项目 - AngularJS / JavaScript Splice - Always deletes first or last item from array Firebase JavaScript - 数组中的映射值仅显示最后一项 - Firebase JavaScript - Mapping values from array only display last item
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM