etc./StackOverFlow

JavaScript에서 값이 객체인지 확인

청렴결백한 만능 재주꾼 2022. 1. 5. 09:43
반응형

질문자 :Danny Fox


JavaScript에서 값이 객체인지 어떻게 확인합니까?



typeof yourVariable === 'object' 이면 객체이거나 null입니다. null 및 배열을 제외하려면 typeof yourVariable === 'object' && yourVariable !== null && !Array.isArray(yourVariable) .


Chuck

업데이트 :

이 답변은 불완전하며 잘못된 결과를 제공합니다 . 예를 들어 null 은 다른 몇 가지 경우는 말할 것도 없고 JavaScript에서 object 유형으로도 간주됩니다. 아래 권장 사항을 따르고 다른 "가장 많이 추천된(그리고 정확한!) 답변"으로 이동하십시오 .

 typeof yourVariable === 'object' && yourVariable !== null

원래 답변 :

typeof(var) 및/또는 var instanceof something 사용해 보십시오.

편집: 이 답변은 변수의 속성을 검사하는 방법에 대한 아이디어를 제공하지만 그것이 객체인지 여부를 확인하기 위한 방탄 레시피 가 아닙니다(결국 레시피가 전혀 없습니다!). 사람들은 조사를 하지 않고 여기에서 복사할 것을 찾는 경향이 있기 때문에 가장 많이 투표된(그리고 정확한) 다른 답변으로 전환하는 것이 좋습니다.


Michael Krelin - hacker

Javascript에서 "객체"를 정의합시다 . MDN 문서 에 따르면 모든 값은 객체 또는 기본형입니다.

원시적, 원시적 값

객체가 아니며 메서드가 없는 데이터입니다. JavaScript에는 문자열, 숫자, bigint, 부울, 정의되지 않음, 기호 및 null의 7가지 기본 데이터 유형이 있습니다.

원시인이 무엇입니까?

  • 3
  • 'abc'
  • true
  • null
  • undefined

객체란 무엇입니까(즉, 기본이 아닌)?

  • Object.prototype
  • Object.prototype 에서 파생된 모든 것
    • Function.prototype
      • Object
      • Function
      • function C(){} -- 사용자 정의 함수
    • C.prototype -- 사용자 정의 함수의 프로토타입 속성: 이것은 C s 프로토타입 이 아닙니다.
      • new C() -- "new"- 사용자 정의 함수 생성
    • Math
    • Array.prototype
      • 배열
    • {"a": 1, "b": 2} -- 리터럴 표기법을 사용하여 생성된 객체
    • new Number(3) -- 프리미티브를 둘러싼 래퍼
    • ... 다른 많은 것들 ...
  • Object.create(null)
  • Object.create(null) 에서 파생된 모든 것

값이 객체인지 확인하는 방법

instanceof 자체는 작동하지 않습니다. 두 가지 경우를 놓치기 때문입니다.

 // oops: isObject(Object.prototype) -> false // oops: isObject(Object.create(null)) -> false function isObject(val) { return val instanceof Object; }

typeof x === 'object' 는 거짓 긍정( null )과 거짓 부정(함수) 때문에 작동하지 않습니다.

 // oops: isObject(Object) -> false function isObject(val) { return (typeof val === 'object'); }

Object.prototype.toString.call 은 모든 기본 요소에 대한 거짓 긍정 때문에 작동하지 않습니다.

 > Object.prototype.toString.call(3) "[object Number]" > Object.prototype.toString.call(new Number(3)) "[object Number]"

그래서 나는 다음을 사용합니다.

 function isObject(val) { if (val === null) { return false;} return ( (typeof val === 'function') || (typeof val === 'object') ); }

@Daan의 답변도 작동하는 것 같습니다.

 function isObject(obj) { return obj === Object(obj); }

MDN 문서 에 따르면

Object 생성자는 주어진 값에 대한 객체 래퍼를 생성합니다. 값이 null이거나 정의되지 않은 경우 빈 개체를 만들어 반환하고, 그렇지 않으면 지정된 값에 해당하는 형식의 개체를 반환합니다. 값이 이미 개체인 경우 값을 반환합니다.


작동하는 것처럼 보이는 세 번째 방법(100%인지 확실하지 않음)은 인수가 객체가 아닌 경우 예외를 발생시키는 Object.getPrototypeOf

 // these 5 examples throw exceptions Object.getPrototypeOf(null) Object.getPrototypeOf(undefined) Object.getPrototypeOf(3) Object.getPrototypeOf('abc') Object.getPrototypeOf(true) // these 5 examples don't throw exceptions Object.getPrototypeOf(Object) Object.getPrototypeOf(Object.prototype) Object.getPrototypeOf(Object.create(null)) Object.getPrototypeOf([]) Object.getPrototypeOf({})

Matt Fenwick

underscore.js 는 무언가가 실제로 객체인지 확인하기 위해 다음 메서드를 제공합니다.

 _.isObject = function(obj) { return obj === Object(obj); };

업데이트

V8의 이전 버그와 사소한 마이크로 속도 최적화로 인해 underscore.js 1.7.0 (2014년 8월)부터 이 메서드는 다음과 같이 보입니다.

 _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; };

Daan

Object.prototype.toString.call(myVar) 은 다음을 반환합니다.

  • myVar가 객체인 경우 "[object Object]"
  • myVar가 배열인 경우 "[object Array]"
  • 등.

이것에 대한 자세한 정보와 이것이 typeof의 좋은 대안인 이유는 이 기사를 확인하십시오 .


Christophe

추가 기능 호출(속도) 없이 단순히 Object 또는 Array에 대해 확인하기 위한 것입니다. 여기에 게시된 대로 .

isArray()

 isArray = function(a) { return (!!a) && (a.constructor === Array); }; console.log(isArray( )); // false console.log(isArray( null)); // false console.log(isArray( true)); // false console.log(isArray( 1)); // false console.log(isArray( 'str')); // false console.log(isArray( {})); // false console.log(isArray(new Date)); // false console.log(isArray( [])); // true

isLiteralObject() - 참고: new Date 또는 new YourCustomObject와 같은 사용자 정의 객체에 대해 false를 반환하므로 객체 리터럴에만 사용하십시오.

 isLiteralObject = function(a) { return (!!a) && (a.constructor === Object); }; console.log(isLiteralObject( )); // false console.log(isLiteralObject( null)); // false console.log(isLiteralObject( true)); // false console.log(isLiteralObject( 1)); // false console.log(isLiteralObject( 'str')); // false console.log(isLiteralObject( [])); // false console.log(isLiteralObject(new Date)); // false console.log(isLiteralObject( {})); // true

zupa

나는 단순히 좋아한다:

 function isObject (item) { return (typeof item === "object" && !Array.isArray(item) && item !== null); }

항목이 JS 객체이고 JS 배열이 아니고 null 이 아닌 경우 … 세 가지가 모두 true로 증명되면 true를 반환 true . 세 가지 조건 중 하나라도 실패하면 && 테스트가 단락되고 false 가 반환됩니다. null 테스트는 원하는 경우 생략할 수 있습니다( null 사용 방법에 따라 다름).

문서:

http://devdocs.io/javascript/operators/typeof

http://devdocs.io/javascript/global_objects/object

http://devdocs.io/javascript/global_objects/array/isarray

http://devdocs.io/javascript/global_objects/null


2540625

Array.isArray 함수 사용:

 function isObject(o) { return o !== null && typeof o === 'object' && Array.isArray(o) === false; }

함수 Array.isArray 없이:

오답에 대한 찬성표가 얼마나 많은지 놀랐습니다.
1개의 답변 만 내 테스트를 통과했습니다!!! 여기에서 단순화된 버전을 만들었습니다.

 function isObject(o) { return o instanceof Object && o.constructor === Object; }

저에 관해서는 명확하고 간단하며 작동합니다! 여기 내 테스트 :

 console.log(isObject({})); // Will return: true console.log(isObject([])); // Will return: false console.log(isObject(null)); // Will return: false console.log(isObject(/.*/)); // Will return: false console.log(isObject(function () {})); // Will return: false

한 번 더: 모든 답변이 이 테스트를 통과하는 것은 아닙니다!!!


객체가 특정 클래스의 인스턴스 인지 확인해야 하는 경우 다음과 같이 특정 클래스로 생성자를 확인해야 합니다.

 function isDate(o) { return o instanceof Object && o.constructor === Date; }

간단한 테스트:

 var d = new Date(); console.log(isObject(d)); // Will return: false console.log(isDate(d)); // Will return: true

결과적으로 엄격하고 강력한 코드를 갖게 됩니다!


isDate , isError , isRegExp 등과 같은 함수를 생성하지 않을 경우 이 일반화된 함수를 사용하는 옵션을 고려할 수 있습니다.

 function isObject(o) { return o instanceof Object && typeof o.constructor === 'function'; }

앞에서 언급한 모든 테스트 케이스에서는 올바르게 작동하지 않지만 모든 객체(일반 또는 구성)에는 충분합니다.


여기서 설명하는 Object.create 의 내부 구현으로 인해 Object.create(null) isObject 가 작동하지 않지만 보다 정교한 구현에서 isObject 를 사용할 수 있습니다.

 function isObject(o, strict = true) { if (o === null || o === undefined) { return false; } const instanceOfObject = o instanceof Object; const typeOfObject = typeof o === 'object'; const constructorUndefined = o.constructor === undefined; const constructorObject = o.constructor === Object; const typeOfConstructorObject = typeof o.constructor === 'function'; let r; if (strict === true) { r = (instanceOfObject || typeOfObject) && (constructorUndefined || constructorObject); } else { r = (constructorUndefined || typeOfConstructorObject); } return r; };

이 구현을 기반으로 npm v1에 이미 생성된 패키지가 있습니다! 그리고 이전에 설명한 모든 테스트 사례에서 작동합니다!


cn007b

세상에! 나는 이것이 그 어느 때보 다 더 짧을 수 있다고 생각합니다. 이것을 봅시다.

짧은 코드와 최종 코드

 function isObject(obj) { return obj != null && obj.constructor.name === "Object" } console.log(isObject({})) // returns true console.log(isObject([])) // returns false console.log(isObject(null)) // returns false

설명

반환 유형

typeof JavaScript 객체( null 포함)는 "object"

 console.log(typeof null, typeof [], typeof {})

그들의 생성자 확인하기

constructor 속성을 확인하면 이름과 함께 함수가 반환됩니다.

 console.log(({}).constructor) // returns a function with name "Object" console.log(([]).constructor) // returns a function with name "Array" console.log((null).constructor) //throws an error because null does not actually have a property

Function.name 소개

Function.name 은 함수의 읽기 전용 이름을 반환하거나 클로저의 경우 "anonymous"

 console.log(({}).constructor.name) // returns "Object" console.log(([]).constructor.name) // returns "Array" console.log((null).constructor.name) //throws an error because null does not actually have a property

참고: 2018년부터 Function.name은 IE 에서 작동하지 않을 수 있습니다. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility


Erisan Olasheni

좋아, 그럼 당신이 대해서 typeof OBJ === '객체'와 같은 간단한 방법이없는 볼 수 있도록로, 또한 객체, 널 (null), 객체, 배열, 심지어 날짜입니다 첫째 자바 스크립트 함수에서, 당신의 질문에 대답하기 전에의 당신에게이 개념을 가집시다 위에서 언급한 모든 것은 true 를 반환하지만 함수를 작성하거나 JavaScript 프레임워크를 사용하여 확인할 수 있는 방법이 있습니다. OK:

이제 실제 객체(null, 함수 또는 배열이 아님)인 이 객체가 있다고 상상해 보십시오.

 var obj = {obj1: 'obj1', obj2: 'obj2'};

순수 자바스크립트:

 //that's how it gets checked in angular framework function isObject(obj) { return obj !== null && typeof obj === 'object'; }

또는

 //make sure the second object is capitalised function isObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; }

또는

 function isObject(obj) { return obj.constructor.toString().indexOf("Object") > -1; }

또는

 function isObject(obj) { return obj instanceof Object; }

위의 함수 중 하나를 호출하여 코드에서 간단히 사용할 수 있으며 객체인 경우 true를 반환합니다.

 isObject(obj);

JavaScript 프레임워크를 사용하는 경우 일반적으로 이러한 종류의 기능이 준비되어 있습니다. 그 중 일부는 다음과 같습니다.

제이쿼리:

 //It returns 'object' if real Object; jQuery.type(obj);

모난:

 angular.isObject(obj);

밑줄 및 Lodash:

 //(NOTE: in Underscore and Lodash, functions, arrays return true as well but not null) _.isObject(obj);

Alireza

그것은 "객체이다"가 무엇을 의미하는지에 달려 있습니다. 기본 이 아닌 모든 것, 즉 새 속성을 설정할 수 있는 것을 원한다면 다음과 같이 해야 합니다.

 function isAnyObject(value) { return value != null && (typeof value === 'object' || typeof value === 'function'); }

기본 요소(일반 숫자/ NaN / Infinity , 일반 문자열, 기호, true / false , undefinednull Number , BooleanString 객체 포함)에 대해서는 true를 반환해야 합니다. window 또는 console typeof 와 함께 사용할 때 반환해야 하는 것을 정의하지 않으므로 이와 같은 검사로 다루기 어렵습니다.

어떤 것이 "일반" 객체인지, 즉 리터럴 {} Object.create(null) 로 생성되었는지 알고 싶다면 다음과 같이 할 수 있습니다.

 function isPlainObject(value) { if (Object.prototype.toString.call(value) !== '[object Object]') { return false; } else { var prototype = Object.getPrototypeOf(value); return prototype === null || prototype === Object.prototype; } }

2018년 편집 Symbol.toStringTag Object.prototype.toString.call(...) 의 출력을 사용자 정의할 수 있기 때문에 위의 isPlainObject 함수는 객체가 리터럴로 수명을 시작한 경우에도 경우에 따라 false 를 반환할 수 있습니다. 틀림없이 관례상 사용자 지정 문자열 태그가 있는 객체는 더 이상 정확히 일반 객체가 아니지만 Javascript에서 일반 객체가 무엇인지에 대한 정의가 더욱 모호해졌습니다.


last-child

맙소사, 다른 답변에 너무 많은 혼란이 있습니다.

짧은 답변

typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array)

이를 테스트하려면 크롬 콘솔에서 다음 명령문을 실행하기만 하면 됩니다.

사례 1.

 var anyVar = {}; typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // true

사례 2.

 anyVar = []; typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // false

사례 3.

 anyVar = null; typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array); // false

설명

알았어.파괴하자

typeof anyVar == 'object' [], {} and null 세 가지 후보에서 true를 반환합니다.

anyVar instanceof Object 이러한 후보를 [], {}

!(anyVar instanceof Array) - {}

드럼 롤 주세요!

이것으로 Javascript에서 Array를 확인하는 방법을 이미 배웠을 것입니다.


HalfWebDev

값의 유형을 확인하는 가장 합리적인 방법은 typeof 연산자인 것 같습니다. 유일한 문제는 그것이 끔찍하게 망가졌다는 것입니다.

  • Null 유형에 속하는 null 에 대해 "object" 를 반환합니다.
  • Object 유형에 속하는 호출 가능한 개체에 대해 "function" 를 반환합니다.
  • 호출할 수 없는 비표준 객체에 대해 원하는 모든 것을 (거의) 반환할 수 있습니다. "unknown" 을 좋아하는 것 같았습니다. 금지된 결과는 "function" 와 기본 유형뿐입니다.

typeof null 이 아닌 기본 요소에 대해서만 신뢰할 수 있습니다. 따라서 값이 객체인지 확인하는 방법은 typeof 반환된 문자열이 기본 형식에 해당하지 않고 객체가 null 이 아닌지 확인하는 것입니다. 그러나 문제는 미래의 표준이 새로운 기본 유형을 도입할 수 있고 우리 코드가 이를 객체로 간주할 수 있다는 것입니다. 새로운 유형은 자주 나타나지 않지만 예를 들어 ECMAScript 6에는 Symbol 유형이 도입되었습니다.

따라서 typeof 대신 값이 객체인지 아닌지에 따라 결과가 달라지는 접근 방식만 권장합니다. 다음은

값이 개체 유형에 속하는지 테스트하는 적절한 방법의 포괄적이지만 완전한 목록은 아닙니다.

  • Object 생성자

    Object 생성자는 전달된 인수를 Object 이미 객체인 경우 동일한 객체가 반환됩니다.

    따라서 이를 사용하여 값을 개체로 강제 변환하고 해당 개체를 원래 값과 엄격하게 비교할 수 있습니다.

    === 를 도입한 ECMAScript 3이 필요합니다.

     function isObject(value) { /* Requires ECMAScript 3 or later */ return Object(value) === value; }

    나는 이 접근 방식이 간단하고 자체 설명적이며 유사한 검사가 부울, 숫자 및 문자열에 대해서도 작동하기 때문에 좋아합니다. 그러나 그림자가 지거나 변경되지 않는 Object 에 의존한다는 점에 유의하십시오.

  • 생성자

    생성자를 인스턴스화하면 방금 생성한 인스턴스와 다른 값을 반환할 수 있습니다. 그러나 그 값은 객체가 아닌 한 무시됩니다.

    다음 함수에는 생성자가 비객체를 반환할 수 있는 ECMAScript 3이 필요합니다. 오류가 발생한 ECMAScript 3 이전에는 try 문이 없었습니다.

     function isObject(value) { /* Requires ECMAScript 3 or later */ return new function() { return value; }() === value; }

    이전 예제보다 약간 덜 간단하지만 이 예제는 전역 속성에 의존하지 않으므로 가장 안전할 수 있습니다.

  • this

    이전 ECMAScript 사양에서는 this 값이 객체여야 했습니다. ECMAScript 3에서는 this 값으로 함수를 호출할 수 있지만 객체로 강제 변환 Function.prototype.call

    ECMAScript 5는 이 동작을 제거한 strict 모드를 도입했지만 sloppy 모드에서 우리는 여전히 그것에 의존할 수 있습니다.

     function isObject(value) { /* Requires ECMAScript 3 or later in sloppy mode */ return function() { return this === value; }.call(value); }
  • [[원기]]

    모든 일반 개체에는 [[Prototype]]이라는 내부 슬롯이 있으며, 이 슬롯의 값은 상속되는 다른 개체에서 결정됩니다. 값은 객체 또는 null 있습니다. 따라서 원하는 값을 상속받은 객체를 생성해 보고 제대로 작동하는지 확인할 수 있습니다.

    Object.createObject.getPrototypeOf 모두 ECMAScript 5가 필요합니다.

     function isObject(value) { /* Requires ECMAScript 5 or later */ try { Object.create(value); return value !== null; } catch(err) { return false; } }
     function isObject(value) { /* Requires ECMAScript 5 or later */ function Constructor() {} Constructor.prototype = value; return Object.getPrototypeOf(new Constructor()) === value; }
  • 몇 가지 새로운 ECMAScript 6 방법

    ECMAScript 6에는 값이 객체인지 확인하는 몇 가지 새로운 간접적인 방법이 도입되었습니다. 그들은 이전에 본 접근 방식을 사용하여 오류를 포착하기 위해 try 문 안에 래핑된 개체가 필요한 일부 코드에 값을 전달합니다. 언급할 가치가 없는 몇 가지 숨겨진 예

     function isObject(value) { /* Requires ECMAScript 6 or later */ try { Object.setPrototypeOf({}, value); return value !== null; } catch(err) { return false; } }

     function isObject(value) { /* Requires ECMAScript 6 or later */ try { new WeakSet([value]); return true; } catch(err) { return false; } }


Object.getPrototypeOf(value) (ES5) 및 Reflect 메서드(ES6)와 같은 일부 접근 방식은 의도적으로 건너뛰었습니다. value 이 프록시인 경우와 같이 불쾌한 작업을 수행할 수 있는 필수 내부 메서드를 호출하기 때문입니다. 안전상의 이유로 내 예제는 직접 액세스하지 않고 value


Oriol

조금 늦었습니다 ... "일반 개체"(예 : {'x': 5, 'y': 7})에 대해 다음과 같은 작은 스 니펫이 있습니다.

 function isPlainObject(o) { return (o === null || Array.isArray(o) || typeof o == 'function' || o.constructor === Date ) ? false :(typeof o == 'object'); }

다음 출력을 생성합니다.

 console.debug(isPlainObject(isPlainObject)); //function, false console.debug(isPlainObject({'x': 6, 'y': 16})); //literal object, true console.debug(isPlainObject(5)); //number, false console.debug(isPlainObject(undefined)); //undefined, false console.debug(isPlainObject(null)); //null, false console.debug(isPlainObject('a')); //string, false console.debug(isPlainObject([])); //array?, false console.debug(isPlainObject(true)); //bool, false console.debug(isPlainObject(false)); //bool, false

그것은 항상 나를 위해 작동합니다. If는 "o" 유형이 "객체"이고 null, 배열 또는 함수가 아닌 경우에만 "true"를 반환합니다. :)


Emilio Grisolía

확인을 위한 기능을 사용할 준비가 되었습니다.

 function isObject(o) { return null != o && typeof o === 'object' && Object.prototype.toString.call(o) === '[object Object]'; } function isDerivedObject(o) { return !isObject(o) && null != o && (typeof o === 'object' || typeof o === 'function') && /^\[object /.test(Object.prototype.toString.call(o)); } // Loose equality operator (==) is intentionally used to check // for undefined too // Also note that, even null is an object, within isDerivedObject // function we skip that and always return false for null

설명

  • Javascript에서 null , Object , Array , Datefunction 은 모두 객체입니다. 그러나 null 은 약간 인위적입니다. null 이 아닌 것을 감지하려면 먼저 null을 확인하는 것이 좋습니다.

  • typeof o === 'object' 확인 o 가 객체임을 보장합니다. 이 검사가 없으면 Object.prototype.toString undefinednull 인 경우에도 모든 것에 대해 객체를 반환하기 때문입니다! 예: toString(undefined) [object Undefined] 반환합니다!

    typeof o === 'object' 검사 후 toString.call(o)은 o Array , Date 또는 function 와 같은 파생 객체인지 확인하는 훌륭한 방법입니다.

  • isDerivedObject 함수에서 o 가 함수인지 확인합니다. 기능도 객체이기 때문에 존재하는 것입니다. 그렇게 하지 않으면 함수는 false로 반환됩니다. 예: isDerivedObject(function() {})false 반환하지만 이제는 true 반환합니다.

  • 객체가 무엇인지에 대한 정의는 언제든지 변경할 수 있습니다. 따라서 이러한 기능을 적절하게 변경할 수 있습니다.


테스트

 function isObject(o) { return null != o && typeof o === 'object' && Object.prototype.toString.call(o) === '[object Object]'; } function isDerivedObject(o) { return !isObject(o) && null != o && (typeof o === 'object' || typeof o === 'function') && /^\[object /.test(Object.prototype.toString.call(o)); } // TESTS // is null an object? console.log( 'is null an object?', isObject(null) ); console.log( 'is null a derived object?', isDerivedObject(null) ); // is 1234 an object? console.log( 'is 1234 an object?', isObject(1234) ); console.log( 'is 1234 a derived object?', isDerivedObject(1234) ); // is new Number(1234) an object? console.log( 'is new Number(1234) an object?', isObject(new Number(1234)) ); console.log( 'is new Number(1234) a derived object?', isDerivedObject(1234) ); // is function object an object? console.log( 'is (new (function (){})) an object?', isObject((new (function (){}))) ); console.log( 'is (new (function (){})) a derived object?', isObject((new (function (){}))) ); // is {} an object? console.log( 'is {} an object?', isObject({}) ); console.log( 'is {} a derived object?', isDerivedObject({}) ); // is Array an object? console.log( 'is Array an object?', isObject([]) ) console.log( 'is Array a derived object?', isDerivedObject([]) ) // is Date an object? console.log( 'is Date an object?', isObject(new Date()) ); console.log( 'is Date a derived object?', isDerivedObject(new Date()) ); // is function an object? console.log( 'is function an object?', isObject(function(){}) ); console.log( 'is function a derived object?', isDerivedObject(function(){}) );


Inanc Gumus

이 시도

 if (objectName instanceof Object == false) { alert('Not an object'); } else { alert('An object'); }

Talha

다음은 선택적 연결에 대한 답변이며 이 질문에 대한 isObj

 const isObj = o => o?.constructor === Object; // True for this console.log(isObj({})); // object! // False for these console.log(isObj(0)); // number console.log(isObj([])); // array console.log(isObj('lol')); // string console.log(isObj(null)); // null console.log(isObj(undefined)); // undefined console.log(isObj(() => {})); // function console.log(isObj(Object)); // class


Jayant Bhawal

당신이 있는지 확인하려는 경우 prototype 에 대한 object 전적으로에서 오는 Object . String , Number , Array , Arguments 등을 Arguments

 function isObject (n) { return Object.prototype.toString.call(n) === '[object Object]'; }

또는 단일 표현식 화살표 함수(ES6+)

 const isObject = n => Object.prototype.toString.call(n) === '[object Object]'

sasi

var a = [1] typeof a //"object" a instanceof Object //true a instanceof Array //true var b ={a: 1} b instanceof Object //true b instanceof Array //false var c = null c instanceof Object //false c instanceof Array //false

자세한 내용을 알려달라는 요청을 받았습니다. 변수가 객체인지 확인하는 가장 깨끗하고 이해하기 쉬운 방법은 typeof myVar 입니다. 유형이 있는 문자열을 반환합니다(예: "object" , "undefined" ).

불행히도 Array 와 null 에도 유형 object 있습니다. instanceof 연산자를 사용하여 상속 체인을 확인할 필요가 있습니다. null을 제거하지만 Array에는 상속 체인에 Object가 있습니다.

따라서 솔루션은 다음과 같습니다.

 if (myVar instanceof Object && !(myVar instanceof Array)) { // code for objects }

Kania

lodash에는 isPlainObject가 있으며 , 이는 이 페이지에 오는 많은 사람들이 찾고 있는 것일 수 있습니다. 함수 또는 배열을 제공하면 false를 반환합니다.


Pat

다른 모든 것이 실패하면 다음을 사용합니다.

 var isObject = function(item) { return item.constructor.name === "Object"; };

Michal

이것은 작동합니다. true, false 또는 null을 반환하는 함수입니다.

 const isObject = obj => obj && obj.constructor && obj.constructor === Object; console.log(isObject({})); // true console.log(isObject([])); // false console.log(isObject(new Function)); // false console.log(isObject(new Number(123))); // false console.log(isObject(null)); // null


pizzarob

Ramda 기능 라이브러리에는 JavaScript 유형을 감지하는 훌륭한 기능이 있습니다.

전체 기능을 바꾸어 말하면:

 function type(val) { return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1); }

솔루션이 얼마나 간단하고 아름다운지 깨달았을 때 나는 웃어야 했습니다.

Ramda 문서의 사용 예:

 R.type({}); //=> "Object" R.type(1); //=> "Number" R.type(false); //=> "Boolean" R.type('s'); //=> "String" R.type(null); //=> "Null" R.type([]); //=> "Array" R.type(/[Az]/); //=> "RegExp" R.type(() => {}); //=> "Function" R.type(undefined); //=> "Undefined"

DaveGauer

이 문제를 올바르게 처리하는 방법에 대해 많은 혼란이 있기 때문에 2센트를 남겨두겠습니다(이 답변은 사양을 준수하며 모든 상황에서 올바른 결과를 생성합니다).

프리미티브 테스트: undefined null boolean string number

 function isPrimitive(o){return typeof o!=='object'||null}

객체는 프리미티브가 아닙니다.

 function isObject(o){return !isPrimitive(o)}

또는 대안:

 function isObject(o){return o instanceof Object} function isPrimitive(o){return !isObject(o)}

모든 어레이에 대한 테스트:

 const isArray=(function(){ const arrayTypes=Object.create(null); arrayTypes['Array']=true; arrayTypes['Int8Array']=true; arrayTypes['Uint8Array']=true; arrayTypes['Uint8ClampedArray']=true; arrayTypes['Int16Array']=true; arrayTypes['Uint16Array']=true; arrayTypes['Int32Array']=true; arrayTypes['Uint32Array']=true; arrayTypes['BigInt64Array']=true; arrayTypes['BigUint64Array']=true; arrayTypes['Float32Array']=true; arrayTypes['Float64Array']=true; return function(o){ if (!o) return false; return !isPrimitive(o)&&!!arrayTypes[o.constructor.name]; } }());

제외 객체 테스트: Date RegExp Boolean Number String Function 모든 배열

 const isObjectStrict=(function(){ const nativeTypes=Object.create(null); nativeTypes['Date']=true; nativeTypes['RegExp']=true; nativeTypes['Boolean']=true; nativeTypes['Number']=true; nativeTypes['String']=true; nativeTypes['Function']=true; return function(o){ if (!o) return false; return !isPrimitive(o)&&!isArray(o)&&!nativeTypes[o.constructor.name]; } }());

c7x43t

JSON , Math , document 또는 프로토타입 체인이 1단계보다 긴 개체와 같은 값을 확인하려고 하는 사람이 거의 없다는 것을 알았습니다.

대신 체크 typeof 우리의 변수를 다음 에지 사례를 멀리 해킹, 나는 검사가 추가 된 새로운 프리미티브 또는 기본 개체가있을 때 리팩토링을 피하기 위해 가능한 한 간단하게 유지하면 좋을 거라고 생각과 레지스터 typeof 의 '물체'.

결국 typeof 연산자는 어떤 것이 JavaScript의 객체 인지 알려줄 것입니다. 그러나 JavaScript의 객체 정의는 대부분의 실제 시나리오에서 너무 광범위합니다(예: typeof null === 'object' ). 다음은 본질적으로 두 가지 검사를 반복하여 v 가 객체인지 여부를 결정하는 함수입니다.

  1. v 의 문자열화된 버전이 '[object Object]' 계속되는 루프가 시작됩니다.
    나는 함수의 결과가 아래 로그와 정확히 같기를 원했기 때문에 이것이 내가 최종적으로 얻은 유일한 "객체성" 기준입니다. 실패하면 함수는 즉시 false를 반환합니다.
  2. v v = Object.getPrototypeOf(v) 체인의 다음 프로토타입으로 대체되지만 이후에 직접 평가됩니다. v 의 새 값이 null 루트 프로토타입( 체인 내부의 유일한 프로토타입일 수 있음)을 포함한 모든 프로토타입 이 while 루프에서 검사를 통과했으며 true를 반환할 수 있음을 의미합니다. 그렇지 않으면 새 반복이 시작됩니다.

 function isObj (v) { while ( Object.prototype.toString.call(v) === '[object Object]') if ((v = Object.getPrototypeOf(v)) === null) return true return false } console.log('FALSE:') console.log('[] -> ', isObj([])) console.log('null -> ', isObj(null)) console.log('document -> ', isObj(document)) console.log('JSON -> ', isObj(JSON)) console.log('function -> ', isObj(function () {})) console.log('new Date() -> ', isObj(new Date())) console.log('RegExp -> ', isObj(/./)) console.log('TRUE:') console.log('{} -> ', isObj({})) console.log('new Object() -> ', isObj(new Object())) console.log('new Object(null) -> ', isObj(new Object(null))) console.log('new Object({}) -> ', isObj(new Object({foo: 'bar'}))) console.log('Object.prototype -> ', isObj(Object.prototype)) console.log('Object.create(null) -> ', isObj(Object.create(null))) console.log('Object.create({}) -> ', isObj(Object.create({foo: 'bar'}))) console.log('deep inheritance -> ', isObj(Object.create(Object.create({foo: 'bar'}))))


Gust van de Wal

내 코드의 목적을 위해 위의 답변 중 일부에 해당하는 이 결정을 찾았습니다.

ES6 변형:

 const checkType = o => Object.prototype .toString .call(o) .replace(/\[|object\s|\]/g, '') .toLowerCase();

ES5 변형:

 function checkType(o){ return Object.prototype .toString .call(o) .replace(/\[|object\s|\]/g, '') .toLowerCase(); }

매우 간단하게 사용할 수 있습니다.

 checkType([]) === 'array'; // true checkType({}) === 'object'; // true checkType(1) === 'number'; // true checkType('') === 'string'; // true checkType({}.p) === 'undefined'; // true checkType(null) === 'null'; // true

등등..


Christiyan

const isObject = function(obj) { const type = typeof obj; return type === 'function' || type === 'object' && !!obj; };

!!obj obj 가 사실인지 확인하기 위한 줄임말입니다 null 을 필터링하기 위해).


Ira

오래된 질문이지만 여기에 남겨둘 생각입니다. 대부분의 사람들은 변수가 {} 가 키-값 쌍을 의미하는지 확인하고 JavaScript가 주어진 항목에 대해 사용하는 밑줄 구성이 아닌 것을 확인합니다. 솔직히 말해서 JavaScript의 대부분은 객체이기 때문입니다. 그래서 그것을 제거합니다. 하면...

 let x = function() {} typeof x === 'function' //true x === Object(x) // true x = [] x === Object(x) // true // also x = null typeof null // 'object'

대부분의 경우 우리가 원하는 것은 API의 리소스 개체가 있는지 또는 ORM에서 반환된 데이터베이스 호출이 있는지 확인하는 것입니다. Array 가 아니고 null 이 아니고 typeof 'function' Object 인지 테스트할 수 있습니다.

 // To account also for new Date() as @toddmo pointed out x instanceof Object && x.constructor === Object x = 'test' // false x = 3 // false x = 45.6 // false x = undefiend // false x = 'undefiend' // false x = null // false x = function(){} // false x = [1, 2] // false x = new Date() // false x = {} // true

Gilbert

성능

오늘 2020.09.26 선택한 솔루션에 대해 Chrome v85, Safari v13.1.2 및 Firefox v80의 MacOs HighSierra 10.13.6에서 테스트를 수행합니다.

결과

  • 솔루션 C 및 H는 모든 경우에 대해 모든 브라우저에서 가장 빠릅니다.
  • 솔루션 D 및 G는 모든 경우에 대해 모든 브라우저에서 느리거나 가장 느립니다.

여기에 이미지 설명 입력

세부

솔루션 A B C D E F G H I J K L M N O P Q R S T U V에 대해 3가지 테스트 케이스를 수행합니다.

아래 스니펫은 솔루션 간의 차이점을 보여줍니다. Solutions AG는 Matt Fenwick이 설명한 선택된 사례에 대해 적절한 답변을 제공합니다.

 // https://stackoverflow.com/a/14706877/860099 function A(x) { return x === Object(x); }; // https://stackoverflow.com/a/42250981/860099 function B(x) { return _.isObject(x); } // https://stackoverflow.com/a/34864175/860099 function C(x) { return x != null && (typeof x === 'object' || typeof x === 'function'); } // https://stackoverflow.com/a/39187058/860099 function D(x) { return new function() { return x; }() === x; } // https://stackoverflow.com/a/39187058/860099 function E(x) { return function() { return this === x; }.call(x); } // https://stackoverflow.com/a/39187058/860099 function F(x) { /* Requires ECMAScript 5 or later */ try { Object.create(x); return x !== null; } catch(err) { return false; } } // https://stackoverflow.com/a/39187058/860099 function G(x) { /* Requires ECMAScript 5 or later */ function Constructor() {} Constructor.prototype = x; return Object.getPrototypeOf(new Constructor()) === x; } // https://stackoverflow.com/a/8511332/860099 function H(x) { return typeof x === 'object' && x !== null } // https://stackoverflow.com/a/25715455/860099 function I(x) { return (typeof x === "object" && !Array.isArray(x) && x !== null); }; // https://stackoverflow.com/a/22482737/860099 function J(x) { return x instanceof Object; } // https://stackoverflow.com/a/50712057/860099 function K(x) { let t= JSON.stringify(x); return t ? t[0] === '{' : false; } // https://stackoverflow.com/a/13356338/860099 function L(x) { return Object.prototype.toString.call(x) === "[object Object]"; }; // https://stackoverflow.com/a/46663081/860099 function M(o, strict = true) { if (o === null || o === undefined) { return false; } const instanceOfObject = o instanceof Object; const typeOfObject = typeof o === 'object'; const constructorUndefined = o.constructor === undefined; const constructorObject = o.constructor === Object; const typeOfConstructorObject = typeof o.constructor === 'function'; let r; if (strict === true) { r = (instanceOfObject || typeOfObject) && (constructorUndefined || constructorObject); } else { r = (constructorUndefined || typeOfConstructorObject); } return r; } // https://stackoverflow.com/a/42250981/860099 function N(x) { return $.type(x) === 'object'; } // https://stackoverflow.com/a/34864175/860099 function O(x) { if (Object.prototype.toString.call(x) !== '[object Object]') { return false; } else { var prototype = Object.getPrototypeOf(x); return prototype === null || prototype === Object.prototype; } } // https://stackoverflow.com/a/57863169/860099 function P(x) { while ( Object.prototype.toString.call(x) === '[object Object]') if ((x = Object.getPrototypeOf(x)) === null) return true return false } // https://stackoverflow.com/a/43289971/860099 function Q(x){ try{ switch(x.constructor){ case Number: case Function: case Boolean: case Symbol: case Date: case String: case RegExp: return x.constructor === Object; case Error: case EvalError: case RangeError: case ReferenceError: case SyntaxError: case TypeError: case URIError: return (Object === Error ? Error : x.constructor) === Object; case Array: case Int8Array: case Uint8Array: case Uint8ClampedArray: case Int16Array: case Uint16Array: case Int32Array: case Uint32Array: case Float32Array: case Float64Array: return (Object === Array ? Array : x.constructor) === Object; case Object: default: return (Object === Object ? Object : x.constructor) === Object; } } catch(ex){ return x == Object; } } // https://stackoverflow.com/a/52478680/860099 function R(x) { return typeof x == 'object' && x instanceof Object && !(x instanceof Array); } // https://stackoverflow.com/a/51458052/860099 function S(x) { return x != null && x.constructor?.name === "Object" } // https://stackoverflow.com/a/42250981/860099 function T(x) { return x?.constructor?.toString().indexOf("Object") > -1; } // https://stackoverflow.com/a/43223661/860099 function U(x) { return x?.constructor === Object; } // https://stackoverflow.com/a/46663081/860099 function V(x) { return x instanceof Object && x.constructor === Object; } // ------------- // TEST // ------------- console.log('column: 1 2 3 4 5 6 - 7 8 9 10 11'); [A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V] .map(f=> console.log(`${f.name}: ${1*f(new Date())} ${1*f(/./)} ${1*f({})} ${1*f(Object.prototype)} ${1*f(Object.create(null))} ${1*f(()=>{})} - ${1*f("abc")} ${1*f(3)} ${1*f(true)} ${1*f(null)} ${1*f(undefined)}`)) console.log(` Columns legend (test cases): 1: new Date() 2: /./ (RegExp) 3: {} 4: Object.prototype 5: Object.create(null) 6: ()=>{} (function) 7: "abc" (string) 8: 3 (number) 9: true (boolean) 10: null 11: undefined Rows: 1 = is object 0 = is NOT object Theoretically columns 1-6 should have have 1, columns 7-11 shoud have 0 `);
 <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script> This shippet only presents functions used in performance tests - it not perform tests itself!

다음은 크롬에 대한 예시 결과입니다.

여기에 이미지 설명 입력


Kamil Kiełczewski

if(typeof value === 'object' && value.constructor === Object) { console.log("This is an object"); }

Mahak Choudhary

출처 : http:www.stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript

반응형