js 에서 대상 유형 을 정확하게 판단 - type: of 와 Object. prototype. toString 방법 에 대한 차이

6837 단어 Javascript
javascript 에 서 는 type of 를 사용 하여 데이터 형식 을 판단 할 수 있 지만 type of 는 기본 형식, 즉 number, string, boolean, undefinded 와 object 등 5 가지 만 판단 할 수 있 습 니 다.
        <script type="text/javascript">
            //      :number、string、boolean、null、undefined
            //      (      ):object(Array、Data、RegExp、function)
            alert(typeof 1);  //number;
            alert(typeof true);  //boolean;
            alert(typeof undefined);  //undefined;
            alert(typeof "hello world")   //string;

            alert(typeof {});  //object;
            alert(typeof null); //object,  null      ;
            alert(typeof function(){});   //function;
        script>

위: null (빈 대상), 배열, {} (대상) 에 대해 type of 를 사용 하여 데이터 형식 을 판단 하면 "object" 문자열 을 통일 적 으로 되 돌려 줍 니 다.
대상 유형 을 정확하게 판단 하려 면 js 의 Object. prototype. toString 방법 을 사용 할 수 있 습 니 다 (판단 대상 은 내 장 된 대상 유형 에 속 합 니 다).
eg:
var arr=[];
console.log(Object.prototype.toString.call(arr));  //     "[object Array]"

ES3 에서 Object. prototype. toString 방법 은 호출 될 때 다음 과 같은 작업 절 차 를 수행 합 니 다. 1. this 대상 의 [Class] 속성의 값 을 가 져 옵 니 다.2. "[object" + "첫 번 째 로 가 져 온 속성 값" + "]" 이 세 문자열 을 연결 한 새 문자열 을 계산 합 니 다.3. 두 번 째 단계 에서 계 산 된 새 문자열 을 되 돌려 줍 니 다.
그 과정 은 쉽게 말 하면 1. 대상 의 유형 (대상 유형) 을 가 져 오 는 것 이다.2. 그리고 [object, 가 져 온 대상 형식의 이름,] 을 문자열 로 조합 합 니 다. "[object Array]" 문자열 을 되 돌려 줍 니 다.
[[Class]] 는 내부 속성 으로 모든 대상 (원생 대상 과 숙주 대상) 이 이 속성 을 가지 고 있 습 니 다. 규범 에서 [Class] 는 이렇게 정의 합 니 다. 내부 속성, [Class] 문자열 값 은 대상 의 유형 을 나 타 냅 니 다.
JavaScript 의 모든 것 이 대상 이기 때문에 예외 가 아 닙 니 다. 모든 값 유형 에 Object. prototype. toString. call () 방법 을 적용 한 결 과 는 다음 과 같 습 니 다.
        <script type="text/javascript">
            console.log(Object.prototype.toString.call(123))    //"[object Number]"
            console.log(Object.prototype.toString.call('123'))    //"[object String]"
            console.log(Object.prototype.toString.call(undefined))    //"[object Undefined]"
            console.log(Object.prototype.toString.call(true))    //"[object Boolean]"
            console.log(Object.prototype.toString.call(null))    //"[object Null]"
            console.log(Object.prototype.toString.call({}))    //"[object Object]"
            console.log(Object.prototype.toString.call([]))    //"[object Array]"
            console.log(Object.prototype.toString.call(function(){}))    //"[object Function]"
        script>

위 에서 보 듯 이 Object. prototype. toString. call () 은 대상 유형 을 정확하게 판단 할 수 있 습 니 다.
함수 인지 아 닌 지 를 판단 하 다
   function isFunction(it) {
        return Object.prototype.toString.call(it) === '[object Function]';
    }

호환성 문제 가 있 습 니 다. 전면적 인 표기 법 은:
 function isArray(arr){  //         isArray(),                ;
                if(typeof Array.isArray === "undefined"){  //Array.isArray() ES5      ,        undefined,              ,    Array.isArray()  ;
                    Array.isArray = function(brr){  //     ,          ;
                        return Object.prototype.toString.call(brr)=="[object Array]"  //  js  Object.prototype.toString  ,      ,               ,   ,    true    ,    ;
                    }
                }
                return Array.isArray(arr);  //     ,  isArray()     Array.isArray();
            }

위 와 같이 판단 배열 이 고 다른 판단 은 유사 하 다.

좋은 웹페이지 즐겨찾기