每天一个小技巧

146 阅读1分钟

JS 获取数组的最后一项:

  1. 使用 pop()
  • pop()方法从数组中删除最后一个元素,并返回该元素的值。
    const arr = ['a','b','c','d','e']
    const lastElement = arr.pop()
    console.log(lastElement) // expected output 'e'
    console.log(arr) // expected output ['a','b','c','d']
    // 如果 原数组为空数组,即 arr = [], 使用 pop() 方法返回值是 undefined
特别提醒: 该方法会改变数组的长度!
  1. 使用 length
  • 基于数组的length 属性获取数组的最后一项元素
    const arr = ['a','b','c','d','e']
    const le = arr[arr.length - 1]
    console.log(le) // expected output 'e'
    console.log(arr) // expected output ['a','b','c','d']

slice 不带参数可以实现浅拷贝:

const arr = [1, 2, 3]

const copy = arr.slice()

每天记录多一点~