Skip to content

เช็ค Value ยังไงไม่ให้บ้ง #16

@rootEnginear

Description

@rootEnginear

NaN

NaN ต้องใช้ isNaN() (Number.isNaN()) เท่านั้น

a = NaN
isNaN(a) // -> true

undefined/null

เช็คตรง (===) ได้เลย

a = undefined
a === undefined // -> true

a = null
a === null // -> true

Primitive อื่นๆ

string (ทั้งเปล่าและไม่เปล่า), number (<เลข>, 0, -0, Infinity, -Infinity ที่ไม่ใช่ NaN), boolean, undefined, null เช็คตรง (===) ได้เลย

ปล. 0 === -0 แต่ในความเป็นจริง -0 ก็คือ 0 แหละ so ¯\_(ツ)_/¯

Array

เช็คว่าว่างไหม ใช้ .length === 0

a = []
a.length === 0 // -> true

เช็คว่าเป็น Array ไหม ใช้ Array.isArray()

a = []
Array.isArray(a) // -> true

Object

เช็คว่ามี property x ไหม ใช้ in — ข้อควรระวังคือ ต่อให้มีแต่ค่าเป็น undefined ก็ถือว่ามี (เพราะเอาไว้เช็คว่ามีไหม)

a = { x: undefined }
x in a // -> true

delete a.x
x in a // -> false

(คห.) ส่วนใหญ่ถ้าจะเช็ครวดไปเลยว่ามี property + ไม่เป็น falsy ก็ . หา property ไปเลย (if (a.x) ...)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions