博客 / 詳情

返回

數組倒序有哪些方法

倒序排列數組的方法如下:

  1. 使用reverse()方法:
const arr = [1, 2, 3, 4, 5];
const reversedArr = arr.reverse();
console.log(reversedArr); //[5, 4, 3, 2, 1]
  1. 使用for循環和unshift()方法:
const arr = [1, 2, 3, 4, 5];
const reversedArr = [];
for (let i = arr.length - 1; i >= 0; i--) {
  reversedArr.push(arr[i]);
}
console.log(reversedArr); //[5, 4, 3, 2, 1]
  1. 使用map()方法:
const arr = [1, 2, 3, 4, 5];
const reversedArr = arr.map((item, index, arr) => arr[arr.length - index - 1]);
console.log(reversedArr); //[5, 4, 3, 2, 1]
  1. 使用reduce()方法:
const arr = [1, 2, 3, 4, 5];
const reversedArr = arr.reduce((accumulator, currentValue) => [currentValue, ...accumulator], []);
console.log(reversedArr); //[5, 4, 3, 2, 1]
user avatar hightopo 頭像 nanian_5cd6881d3cc98 頭像 niumingxin 頭像 hachimei 頭像 liuxuan_5845129fbf248 頭像 yzbao 頭像 kumendejianpan 頭像 laomao_5902e12974409 頭像 tangzhiyuan 頭像 Leesz 頭像 haikuotiankong_mac 頭像 aoshizhongshengdesongshu_68fcd9327eb2a 頭像
15 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.