Skip to content

数组反转

数组反转

示例

输入:[1, 2, 3]

输出:[3, 2, 1]

代码

javascript
// 输入:[1, 2, 3]
// 输出:[3, 2, 1]

export function arrayReverse (arr) {
  const res = []
  for (let i = arr.length -1; i > -1; i--) {
    res.push(arr[i])
  }
  return res
}
typescript
// 输入:[1, 2, 3]
// 输出:[3, 2, 1]

export function arrayReverse <T>(arr: T[]): T[] {
  const res = []
  for (let i = arr.length -1; i > -1; i--) {
    res.push(arr[i])
  }
  return res
}

测试代码

ts
import { expect, test } from 'vitest'
import { arrayReverse } from './typescript.ts'
import { arrayReverse as arrayReverseJs } from './javascript.js'

test(`[1, 2, 3] toEqual [3, 2, 1]`, () => {
  expect(arrayReverse([1, 2, 3])).toEqual([3, 2, 1])
})

test(`[1, 2, 3] toEqual [3, 2, 1]`, () => {
  expect(arrayReverseJs([1, 2, 3])).toEqual([3, 2, 1])
})