動態

詳情 返回 返回

數組倒序有哪些方法 - 動態 詳情

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

  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 haoqidewukong 頭像 linlinma 頭像 yinzhixiaxue 頭像 dirackeeko 頭像 banana_god 頭像 febobo 頭像 woniuseo 頭像 yqyx36 頭像 bugDiDiDi 頭像 romanticcrystal 頭像 it1042290135 頭像 licin 頭像
點贊 103 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.