1
0

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 1 year has passed since last update.

JavaScriptで配列最後の要素を取得する

Posted at

Javascript では配列最後の要素を取得する方法がいくつかあったのでまとめておきます。

array[array.length - 1]

今まではこれを使うのが多かったそうです。

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits[fruits.length - 1]); // orange

array.pop()

これで取得すると、元の配列から最後の要素が消えてしまいます。

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.pop()); // orange
console.log(fruits); // ['apple', 'banana']

array.slice(-1)[0]

これでも取得できますが、何をしているコードか分かりづらいです。

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.slice(-1)[0]); //orange

array.at()

ES2022 で at() メソッドが追加されたので、これを使うのが一番簡単そうです。

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits[0]); // apple
console.log(fruits[-1]); // undefined
console.log(fruits.at(0)); // apple
console.log(fruits.at(-1)); // orange

参考

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
https://qiita.com/kerupani129/items/64ce1e80eb8efb4c2b21

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?