j s 중 유형 검사 방법

1392 단어 nodejs
js 에서 의 유형 검 측 현재 내 가 알 고 있 는 것 은 세 가지 방식 으로 각각 그들의 응용 장면 이 있다.
1. typeof: 기본 유형 을 검사 하 는 데 사 용 됩 니 다.
typeof undefined;//=> undefined
typeof 'a';//=> string
typeof 1;//=> number
typeof true;//=> boolean
typeof {};//=> object
typeof [];//=> object
typeof function() {};//=> function
typeof null;//=> object
2. instanceof: 인용 형식 을 검사 하 는 데 사 용 됩 니 다 (왼쪽 은 대상 이 고 오른쪽 은 함수 입 니 다. 대상 의 원형 체인 에 따라 위로 찾 습 니 다. 원형 체인 에 오른쪽 함수 가 있 으 면 prototype 은 true 로 돌아 갑 니 다. 그렇지 않 으 면 false 로 돌아 갑 니 다)
var obj = {}; obj instanceof Object; //=> true; 
var arr = []; arr instanceof Array; //=> true;
var fn = function() {}; fn instanceof Function; //=> true;

3. Object. prototype. toString. call (sth): 원형 체인 의 검 측 에 구멍 이 있 기 때문에 검 측 결과 가 정확 하지 않 기 때문에 이 형식 을 사용 할 수 있 습 니 다.
var toString = Object.prototype.toString;
toString.call(undefined);//=> [object Undefined]
toString.call(1);//=> [object, Number]
toString.call(NaN);//=> [object, Number]
toString.call('a');//=> [object, String]
toString.call(true);//=> [object, Boolean]
toString.call({});//=> [object, Object]
toString.call(function() {});//=> [object, Function]
toString.call([]);//=> [object, Array]
toString.call(null);//=> [object, Null]

좋은 웹페이지 즐겨찾기