xxleyi / learning_list

聚集自己的学习笔记
10 stars 3 forks source link

JS 类型判断 #214

Open xxleyi opened 4 years ago

xxleyi commented 4 years ago

啊,JS 真是一门复杂的语言,判断个变量类型还得先略懂最艰深的核心概念才能行:

较为浅显易懂的一篇: Why Object.prototype.toString.call()?

Object.prototype.toString And Its Uses

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString()method is inherited by every object descended from Object. If this method is not overridden in a custom object,toString() returns “[object type]”, where type is the object type.

So in order to tell arrays from pure objects, Object.prototype.toString() is the one we need.

var toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]
toString.call(''); // [object String] because of object box
toString.call([]); [object Array]

//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]

更古老但也更有深度的一篇:Fixing the JavaScript typeof operator – JavaScript, JavaScript…