0
1

【JavaScript】配列の最後の要素を取り出すメソッド

Last updated at Posted at 2022-09-16

追記

今はatメソッドを使いましょう。

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

本題

次のメソッドを作ってください。

Array.prototype.last = function() {
    if (this.length === 0) {
        throw new Error("要素が存在しない");
    }
    return this[this.length - 1];
};

簡単に最後の要素が取り出せるようになります。

const hogeArray = [1, 1, 2, 3, 5, 8];
console.log(hogeArray.last()); // 8
0
1
0

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
1