Help us understand the problem. What is going on with this article?

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

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]
toooy
グラフィックデザイン・イラストが好きなデザイナー。 UIUXとフロントエンド中心に学習した事をメモします(たまに動画関連)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away