动态

详情 返回 返回

數組倒序有哪些方法 - 动态 详情

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

  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.