42
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

array.at() でスマートに配列の要素を取り出そう

Last updated at Posted at 2025-02-10

はじめに

ここでは、array.at() を使うメリットや使い方を紹介します。
例えば、JavaScriptで、配列の最後の要素を取りたい時、array[array.length - 1] ではなく at(-1) を使うことで、コードの可読性を上げられます。

サクッと理解して、よりスマートなコードをかけるようにしましょう!

概要

  • ポイント1: array.length - 1 を使う代わりに at(-1) を使うと、コードが短く読みやすい
  • ポイント2: マイナスのインデックス指定ができるので、直感的に「後ろから何番目か」を参照できる
  • ポイント3: ES2022(ES13)で追加された新機能

内容

なぜ at(-1) がいいのか?

従来、配列の最後の要素を取り出すためには次のように書いていました。

const array = [1, 2, 3, 4, 5];
console.log(array[array.length - 1]); // 5

このとき、コードが少し冗長になってしまいますね。

そこでES2022から登場した Array.prototype.at() メソッドを使うと、負の整数で後ろから要素を取り出せます。
最後の要素を参照したい場合は at(-1) を使いましょう。

const array = [1, 2, 3, 4, 5];
console.log(array.at(-1)); // 5

at() メソッドの使い方

at() は配列の要素に対して、以下のようにアクセスが可能です。

const array = ['apple', 'banana', 'orange', 'grape'];

console.log(array.at(0));   // 'apple'  (最初の要素)
console.log(array.at(1));   // 'banana' (2番目)
console.log(array.at(-1));  // 'grape'  (最後の要素)
console.log(array.at(-2));  // 'orange' (後ろから2番目)

このように、プラスのインデックスで先頭から、マイナスのインデックスで末尾から要素を取得できます。

まとめ

  1. array[array.length - 1] よりも array.at(-1) のほうが直感的で読みやすい
  2. 他にも array.at(-2) などで直感的に「後ろから何番目」を参照できる

最後に

少しの書き方の違いですが、スマートに書けています。
これを機に array.at() を活用してみてください!

42
21
3

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
42
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?