JSのデータ型の判定方法

JavaScriptのデータ型

  • 文字列: 文字列
  • 番号: 番号
  • ブール値: ブール値
  • 未定義: 未定義
  • null: 空の値
  • オブジェクト: オブジェクト (配列と関数を含む)
  • シンボル: シンボル、一意の値 (ES6 新機能)

1. typeofの欠陥

typeofstringnumberbooleanundefinedsymbolなどの種類は判断できますfunctionが、 の種類は判断できませnullobject

var str = "Hello";
var num = 123;
var bool = true;
var undf;
var nl = null;
var obj = {
    
    name: "John", age: 25};
var arr = [1, 2, 3];
var func = function() {
    
    };
var sym = Symbol("mySymbol");

console.log(typeof str);    // 输出:string
console.log(typeof num);    // 输出:number
console.log(typeof bool);   // 输出:boolean
console.log(typeof undf);   // 输出:undefined
console.log(typeof nl);     // 输出:object
console.log(typeof obj);    // 输出:object
console.log(typeof arr);    // 输出:object
console.log(typeof func);   // 输出:function
console.log(typeof sym);    // 输出:symbol

注: typeofは区別できませんtypeof は、3 つの型がすべて「object」を返すと判断します。nullObjectArray

2. 配列かどうかを判断する

方法1

instanceofデータが配列であるかどうかを判断するために使用します。

[] instanceof Array // true

instanceof配列もオブジェクトであるため、オブジェクト型であるかどうかを判断することはできないことに注意してください。

[] instanceof Object // true
{
    
    } instanceof Object // true

方法 2

コンストラクターは、それが配列であるかどうかを判断することもできます。

[].constructor === Array // true

方法 3

Object.prototype.toString.call()さまざまな種類のオブジェクトを取得できます。

Object.prototype.toString.call([]) === '[object Array]' // true
Object.prototype.toString.call({
    
    }) === '[object Object]' // true

このメソッドは、Promise オブジェクトであるかどうかを判断するためにも使用できます。

let obj = new Promise()
Object.prototype.toString.call(obj) === '[object Promise]' // true

方法 4

配列の isArray() メソッドを使用して判断します。

Array.isArray([]) // true

方法5

Object.getPrototypeOf(val) === Array.prototype // true 

3.物体かどうかの判断

方法 1 (推奨)

Object.prototype.toString.call() さまざまな種類のオブジェクトを取得できます。

Object.prototype.toString.call({
    
    }) === '[object Object]' // true

方法 2

Object.getPrototypeOf(val) === Object.prototype // true 

おすすめ

転載: blog.csdn.net/m0_53808238/article/details/130640681