この記事は、「新人クリエーションセレモニー」イベントに参加し、一緒にゴールドクリエーションの道を歩み始めました。
序文
jsの型分類と判断方法、typeofとinstanceofの使用法、および既存の問題を記録し、最後にObject.prototype.toString.call()を使用して型を正確に判断する方法を紹介します。
jsタイプ
-
jsには多くの種類があり
内置类型
、組み込み型は2つのカテゴリに分類され基本数据类型
ます复杂==对象(Object)类型
。 -
基本
Null
的Undefined
なデータ型:Number
、、、、、、、、String
。(2022/2/16の時点で、SymbelとBigIntが比較的新しい導入であるように、より基本的なデータ型が将来導入される可能性があります。基本的なデータ型は5つだけです)Boolean
Symbel
BigInt
typeof
- 基本データ型をテストします。nullがオブジェクトとして判断されることを除いて、結論を覚えておいてください。他の基本型は判断できるため、判断に使用することはできません
null
。console.log( typeof null,// object typeof 123,//或 Number(123),// number typeof undefined,// undefined typeof "str",//或 String('str'),// string typeof true,//或 Boolean(true)// boolean typeof Symbol(1),// symbol typeof 12345678910n,//或 BigInt(12345678910),// bigint ); 复制代码
- グループ、オブジェクト、組み込みオブジェクト、新しい関数宣言オブジェクト、関数などの複雑なオブジェクトのタイプを測定します。関数が関数として正しく判断されることを除いて、結論を覚えておいてください。他のすべてはオブジェクトであるため、
除了函数之外
複雑なタイプは判断には使用できません。区別のタイプは使用できません。console.log( typeof [],//object typeof {},//object typeof Math,//object typeof new String(),//object typeof (() => {}),//function ); 复制代码
instanceof
-
まず、instanceofは基本的なデータ型を判断できず、判断したいコンテンツの種類を直接取得することはできず、特定の種類かどうかしか判断できないことは明らかです。
-
これを使用して、それが複雑なオブジェクトタイプであるかどうかを判断できます。
console.log(
[] instanceof Array, //true
{} instanceof Object, //true
new Date() instanceof Date, //true
(() => {}) instanceof Function, //true
)
复制代码
- 因为它的原理是原型链,所以存在一个问题,就是Object的原型作为原型链的终点,js的复杂类型本质也都是对象,因此判断他们是否是对象,也都为true。
console.log(
[] instanceof Object, //true
{} instanceof Object, //true
new Date() instanceof Object, //true
(() => {}) instanceof Object, //true
)
复制代码
精准判断
- .想要精准判断类型,建议使用
Object.prototype.toString.call()
。console.log( Object.prototype.toString.call(null), //[object Null] Object.prototype.toString.call("123"), //[object String] Object.prototype.toString.call(123), //[object Number] Object.prototype.toString.call(undefined), //[object Undefined] Object.prototype.toString.call(true), //[object Boolean] Object.prototype.toString.call(Symbol(1)), //[object Symbol] Object.prototype.toString.call(BigInt(1)), //[object BigInt] Object.prototype.toString.call(() => {}), //[object Function] Object.prototype.toString.call([]), //[object Array] Object.prototype.toString.call({}), //[object Object] Object.prototype.toString.call(Math), //[object Math] Object.prototype.toString.call(new String()) //[object String] ); 复制代码
尾言
如果觉得文章对你有帮助的话,欢迎点赞收藏哦,有什么错误或者意见建议也可以留言,感谢~