js 에서 대상 유형 을 정확하게 판단 - type: of 와 Object. prototype. toString 방법 에 대한 차이
6837 단어 Javascript
<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();
}
위 와 같이 판단 배열 이 고 다른 판단 은 유사 하 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
java,python,JavaScript 및 jquery 순환 문장의 차이2. 자바 순환 문장 조건 문장이 무엇이든지 간에 코드 블록은 최소한 한 번 실행되고do/while 순환을 사용할 수 있습니다.do/while 문법: 즉, 코드 블록을 먼저 집행한 다음에 조건이 성립되었는지 판단하고...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.