34
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

配列の先頭 / 末尾の要素を取得する[Javascript]

Last updated at Posted at 2018-11-18

元の配列を破壊してもいいとき

Array.prototype.shift() や Array.prototype.pop() を利用します。

const arr = [1, 2, 3, 4, 5]
console.log(arr.shift()) // 1
console.log(arr) // [2, 3, 4, 5]
console.log(arr.pop()) // 5
console.log(arr) // [2, 3, 4]

Array.prototype.pop

Array.prototype.shift

元の配列を破壊したくないとき

先頭の要素は添え字[0]、末尾の要素は添え字を[Array.length - 1]として取得できます。

それ以上に必要な場合はArray.prototype.slice() で必要な分だけ切り取ります。
Array.prototype.slice() は、新しい「配列」を返す関数なので、
値が必要な場合はさらにそのインデックスを指定する必要があります。

const arr = [1, 2, 3, 4, 5]

console.log(arr[0]) // 1
console.log(arr[arr.length - 1]) // 5

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

Array.prototype.slice

34
29
2

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
34
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?