LoginSignup
0
0

More than 3 years have passed since last update.

JS 配列の一番最後以外の要素を返す

Last updated at Posted at 2020-08-05

lodashのinitial関数を作ってみた

lodashのinitial関数

const initial = (array) => {
  const initialArray = []
  for (let i = 0; i < array.length - 1; i++) {
    initialArray.push(array[i])
  }
  return initialArray
}

console.log(initial([1, 2, 3, 4]))
// => [ 1, 2, 3, 4, 5 ]

▼POPメゾッドを使うともっと簡潔に書けるみたいだった

const initial = (array) => {
  const copedArray = [...array]

  //popメゾッドは末尾の要素を取り除く
  copedArray.pop()
  return copedArray
}

console.log(initial([1, 2, 3, 4]))
// => [ 1, 2, 3]

▼1行で記述可能だった!

@il9437さん、ありがとうございます!

console.log([1, 2, 3, 4].slice(0, -1))
// => [1, 2, 3]
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0