简体   繁体   English

检查值是对象文字吗?

[英]Check that value is object literal?

I have a value and want to know if it's an iteratable object literal, before I iterate it.我有一个值,想知道它是否是可迭代的对象文字,然后再迭代它。

How do I do that?我怎么做?

This should do it for you:这应该为你做:

if( Object.prototype.toString.call( someObject ) === '[object Object]' ) {
    // do your iteration
}

From ECMAScript 5 Section 8.6.2 if you're interested:如果您有兴趣,可以从ECMAScript 5 第 8.6.2 节

The value of the [[Class]] internal property is defined by this specification for every kind of built-in object. [[Class]] 内部属性的值由本规范为每种内置对象定义。 The value of the [[Class]] internal property of a host object may be any String value except one of "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", and "String".宿主对象的 [[Class]] 内部属性的值可以是任何字符串值,除了“Arguments”、“Array”、“Boolean”、“Date”、“Error”、“Function”、“JSON”之一、“数学”、“数字”、“对象”、“RegExp”和“字符串”。 The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. [[Class]] 内部属性的值在内部用于区分不同种类的对象。 Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see 15.2.4.2).请注意,除了通过 Object.prototype.toString(见 15.2.4.2)之外,本规范没有为程序提供任何访问该值的方法。

You could also do something like:您还可以执行以下操作:

    if (someObject.constructor == Object) {
        // do your thing
    }

you can read more about it here你可以在这里阅读更多关于它的信息

I think a function like this should be native, just like Array.isArray :我认为这样的函数应该是原生的,就像Array.isArray

Object.isObject = function(obj) {
    return obj && obj.constructor === this || false;
};

This one doesn't make function calls nor string comparisons, and doesn't reference global objects (like Object ), so it should be quite fast.这个不进行函数调用或字符串比较,也不引用全局对象(如Object ),所以它应该很快。 I don't think this will used in performance intensive tasks though, but whatever.我认为这不会用于性能密集型任务,但无论如何。

I'm not totally convinced about the name... maybe something like Object.isLiteral would be better.我并不完全相信这个名字......也许像Object.isLiteral这样的东西会更好。

It can cause problem with host objects, though, but I don't have a test ready.不过,它可能会导致主机对象出现问题,但我还没有准备好测试。

Say you have some testvar and want to see if it is an object, but not an array or null (these are both of type Object).假设您有一些testvar并想查看它是否是一个对象,而不是一个数组或 null(它们都是 Object 类型)。 You can do the following您可以执行以下操作

testVar instanceof Object && !Array.isArray(testVar) && testVar !== null

If you use obj instanceof Object or typeof obj === "object" you get false positives on things like new Number(3) and arrays ( [1,2,3] ).如果你使用obj instanceof Objecttypeof obj === "object"你会得到诸如new Number(3)和数组 ( [1,2,3] ) 的误报。

Using o.constructor === Object is great, however there's a weird edge case of Object.create(null) – which does, in fact, give you a plain object, albeit not one created in a "normal" way.使用o.constructor === Object很棒,但是Object.create(null)有一个奇怪的边缘情况——事实上,它确实给了你一个普通对象,尽管不是以“正常”方式创建的。 Conceptually it gives a valid, normal, undecorated object.从概念上讲,它给出了一个有效的、正常的、未修饰的对象。 We check for this case with Object.getPrototypeOf(o) === null which will only hold true for the above undecorated object type.我们使用Object.getPrototypeOf(o) === null检查这种情况,它仅适用于上述未修饰的对象类型。

The !!o converts null or undefined to false . !!onullundefined转换为false People were complaining about it above, and honestly o && ... is more succinct and unless you're serializing it doesn't matter.人们在上面抱怨它,老实说o && ...更简洁,除非你正在连载它并不重要。 Nevertheless, I included it.尽管如此,我把它包括在内。

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

function isObject1(o) {
  return !!o && o.constructor === Object
}

function isObject2(o) {
  // edge case where you use Object.create(null) –– which gives an object {} with no prototype
  return !!o && (Object.getPrototypeOf(o) === null || o.constructor === Object)
}

Strangely, I'm seeing different values for toString() for a subclassed object depending how toString() is being called:奇怪的是,根据 toString() 的调用方式,我看到子类对象的 toString() 值不同:

Object.prototype.toString.call(aThing)
"[object Object]"

aThing.toString()
"ZmPopupMenu"

That results in a false positive, so I amended it to prefer the object's toString():这会导致误报,因此我将其修改为更喜欢对象的 toString():

var str = someObject.toString
    ? someObject.toString()
    : Object.prototype.toString.call(someObject);
return str === '[object Object]';

Well, you don't need to check everything by yourself or write your own codes, when there are good libraries such as Lodash and Underscore .好了,你不需要自己检查一切,或写自己的代码,当有好的库,如Lodash下划线

In Lodash, you can easily check it by isPlainObject function, eg:在 Lodash 中,您可以通过 isPlainObject 函数轻松检查它,例如:

_.isPlainObject({'a': 12});

Check this page: https://lodash.com/docs#isPlainObject检查此页面: https : //lodash.com/docs#isPlainObject

Vanilla Javascript version of JQuery.isPlainObject function. JQuery.isPlainObject函数的原生 Javascript 版本。

var class2type = {};
var toString = class2type.toString;
var getProto = Object.getPrototypeOf;
var hasOwn = class2type.hasOwnProperty;
var fnToString = hasOwn.toString;
var ObjectFunctionString = fnToString.call(Object);

function isPlainObject(obj) {
  var proto, Ctor;

  // Detect obvious negatives
  // Use toString instead of jQuery.type to catch host objects
  if (!obj || toString.call(obj) !== "[object Object]") {
    return false;
  }

  proto = getProto(obj);

  // Objects with no prototype (e.g., `Object.create( null )`) are plain
  if (!proto) {
    return true;
  }

  // Objects with prototype are plain iff they were constructed by a global Object function
  Ctor = hasOwn.call(proto, "constructor") && proto.constructor;
  return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString;
}

Example:例子:

isPlainObject({}) // true
isPlainObject( "test" ) // false
const isObject = (x) => {
  return Object.prototype.toString.call(x) == "[object Object]";
}

That works for me.这对我行得通。

adding to user user113716: (public utility)添加到用户user113716:(公用事业)

function typeOfObj(obj) {
    if(obj === null) return 'null';
    if(typeof obj === 'function' && String(obj).search('class') === 0) return 'class';
    return Object.prototype.toString.call(obj).replace(/.*\w*\s(\w*).*/,'$1').toLowerCase();
}

if(typeof obj !== 'undefined' && typeOfObj(obj) == 'object') true;

Bumping old thread, but it's still shows up in searches and people are even referencing it as duplicate for a new similar ones - and still the top-most answers here are far from being correct (sorry people, no offends).撞到旧线程,但它仍然出现在搜索中,人们甚至将其引用为新的类似线程的重复 - 而且这里最重要的答案仍然远非正确(对不起,人们,没有冒犯)。

To check if variable is an object the following should be used:要检查变量是否是对象,应使用以下内容:

if (typeof variable === 'object') {
    // do something
}

Arrays are also objects, so this would be true for an array too.数组也是对象,因此对于数组也是如此。 Moreover - null is a valid object as well, therefore the above will return true on null too.此外 - null也是一个有效的对象,因此上面的内容也会在null上返回 true。 Personally, when really need to check if an expected variable is 'workable' object I'm always using this boringly repeated formula:就个人而言,当真的需要检查预期变量是否是“可行”对象时,我总是使用这个无聊重复的公式:

if (variable && typeof variable === `object`) {
    // do something
}

Last but not least :) please please please, do yourself a favor and don't use any libraries for such a simple things.最后但并非最不重要的 :) 请拜托,帮自己一个忙,不要将任何库用于如此简单的事情。 Javascript is a fastly evolving language having today much much more than yesterday, so fast that most of the libraries are not even fast enough to fetch up. Javascript 是一种快速发展的语言,今天的发展速度比昨天要快得多,以至于大多数库甚至都不够快,无法获取。 Beside it, people who are working on the spec are doing a great job and mostly the native APIs are clean, correct, making perfect sense and coherent with the rest of the language.除此之外,从事规范工作的人做得很好,而且大多数原生 API 都是干净、正确的,非常有意义并且与语言的其余部分保持一致。

Little gist, not really elegant but efficient小要点,不是很优雅但很有效

function _isObj( _obj ){

   return ( typeof _obj === "object" && JSON.stringify( _obj ).indexOf( "{" ) == 0 ); 

}

Little example小例子

 function _isObj( _obj ){ return ( typeof _obj === "object" && JSON.stringify( _obj ).indexOf( "{" ) == 0 ); } var p = document.createElement( "p" ); p.textContent = "undefined : " + _isObj( undefined ); document.body.appendChild( p ); p = document.createElement( "p" ); p.textContent = "null : " + _isObj( null ); document.body.appendChild( p ); p = document.createElement( "p" ); p.textContent = "boolean : " + _isObj( true ); document.body.appendChild( p ); p = document.createElement( "p" ); p.textContent = "function : " + _isObj( function(){} ); document.body.appendChild( p ); p = document.createElement( "p" ); p.textContent = "array : " + _isObj( [] ); document.body.appendChild( p ); p = document.createElement( "p" ); p.textContent = "string : " + _isObj( "{}" ); document.body.appendChild( p ); document.body.appendChild( p ); document.body.appendChild( p ); p = document.createElement( "p" ); p.textContent = "number : " + _isObj( 1 ); document.body.appendChild( p ); document.body.appendChild( p ); p = document.createElement( "p" ); p.textContent = "object : " + _isObj( {} ); document.body.appendChild( p ); p = document.createElement( "p" ); p.textContent = "another object : " + _isObj( p ); document.body.appendChild( p );

hope this help希望这有帮助

This works for me:这对我有用:

function isObject(o) {
    try {
        return ((typeof o == "object") && (o !== null) && (o.length === undefined));
    } catch (err) {
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM