2013-04-16 3 views
1

배열과 객체 만 입력 할 수 있습니다. 변수가 배열인지 객체인지를 결정할 수있는 간단한 함수가 있습니까?배열 또는 객체인지 확인하려면 어떻게합니까?

+1

이것을 확인하셨습니까? - http://stackoverflow.com/questions/8834126/how-to-efficiently-check-if-variable-is-array-or-object-in-nodejs-v8 –

+0

http://blog.niftysnippets.org/2010 /09/say-what.html .. – alwaysLearn

답변

2
나는 많은 다른 유사한 답가 의심

그러나 이것은 하나의 방법입니다 :이 멋진 기능으로 전환 할 수

if ({}.toString.call(obj) == '[object Object]') { 
    // is an object 
} 

if ({}.toString.call(obj) == '[object Array]') { 
    // is an array 
} 

:

: 이것은 모든 유형의 작동

function typeOf(obj) { 
    return {}.toString.call(obj).match(/\w+/g)[1].toLowerCase(); 
} 

if (typeOf(obj) == 'array') ... 

if (typeOf(obj) == 'date') // is a date 
if (typeOf(obj) == 'number') // is a number 
... 
+0

+1의 가치가 있지만,'Object.prototype.toString'을 사용해야합니다. global/window 객체의 toString 메소드가 적절한 결과를 생성하지 않을 수 있습니다. :-) – RobG

+0

나는 그것이 얼마나 많은 브라우저 지원이 필요한지에 달려 있다고 생각한다. 이것은 최신 브라우저 AFAIK에서 작동합니다. 기본값은 객체 인'window.toString'입니다. 그렇지 않으면'{} .toString'을 선호합니다. 하지만 당신 말이 맞아. – elclanrs

+0

Firefox에서 'window.toString.call (obj)'는'[xpconnect wrapped native prototype]'을 반환합니다. 'window'는 호스트 객체이기 때문에 네이티브 객체에 대한 규칙을 따르지 않아야합니다. 또한, [전역 객체] (http://www.ecma-international.org/ecma-262/5.1/#sec-15.1)는 객체의 인스턴스가 아닙니다 ([[Prototype]] 'ECMA-262에 의해 정의 된 속성 중 하나), 다른 객체보다 먼저 존재하는 특별한 객체입니다. – RobG

1

(variable instanceof Array)은 배열에 대해 true를 반환합니다.

variable.isArray()을 사용할 수도 있지만 이전 브라우저에서는 지원되지 않습니다.

1

당신은 Array.isArray()를 사용할 수 있습니다

if(Array.isArray(myVar)) { 
    // myVar is an array 
} else { 
    // myVar is not an array 
} 

는만큼 당신이 알고있는대로 하나가 설정되어 다른 것입니다. 그것이 instanceof 배열입니다

if(typeof myVar === "object") { 
    if(Array.isArray(myVar)) { 
     // myVar is an array 
    } else { 
     // myVar is a non-array object 
    } 
} 
1

먼저 선택하면 다음 경우 개체 유형의 : 그렇지 않으면, typeof과이 결합되어 있습니다.

if(variable instanceof Array) 
{ 
//this is an array. This needs to the first line to be checked 
//as an array instanceof Object is also true 

} 
else if(variable instanceof Object) 
{ 
//it is an object 
} 
+0

개체가 Array 및 Object의 다른 인스턴스에서 만들어 지므로 프레임을 가로 질러 전달되는 경우 오류가 발생합니다. – RobG

관련 문제