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.

LeetCode 2619. Array Prototype Lastの解き方

Posted at

配列の最後の要素を返す問題です。空配列の場合は-1で返します。

自分の解き方

Array.prototype.last = function() {
    if (!Array.isArray(this)) {
        return
    }

    const result = this.length === 0 ? -1 : this[this.length -1]


    return result 
};

ベターな解放

よくよく考えたら、数値の0はfalseとみなされるのでわざわざ、this.length ===0と書く必要はなかった。

const result = this.length ? this[this.length -1] : 0
return result

falseとみなされる値

  • 0
  • -0
  • 空文字('')
  • 0n
  • null
  • undefinend
  • NaN
1
0
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
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?