[英]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.