javascript 检查该值是否为对象字面量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4320767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check that value is object literal?
提问by ajsie
I have a value and want to know if it's an iteratable object literal, before I iterate it.
我有一个值,想知道它是否是可迭代的对象文字,然后再迭代它。
How do I do that?
我怎么做?
回答by user113716
This should do it for you:
这应该为你做:
if( Object.prototype.toString.call( someObject ) === '[object Object]' ) {
// do your iteration
}
From ECMAScript 5 Section 8.6.2if 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. 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". The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. 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).
[[Class]] 内部属性的值由本规范为每种内置对象定义。宿主对象的 [[Class]] 内部属性的值可以是任何字符串值,除了“Arguments”、“Array”、“Boolean”、“Date”、“Error”、“Function”、“JSON”之一、“数学”、“数字”、“对象”、“RegExp”和“字符串”。[[Class]] 内部属性的值在内部用于区分不同种类的对象。请注意,除了通过 Object.prototype.toString(见 15.2.4.2)之外,本规范没有为程序提供任何访问该值的方法。
回答by dcestari
回答by MaxArt
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. I don't think this will used in performance intensive tasks though, but whatever.
这个不进行函数调用,也不进行字符串比较,也不引用全局对象(如Object),所以它应该很快。我认为这不会用于性能密集型任务,但无论如何。
I'm not totally convinced about the name... maybe something like Object.isLiteralwould be better.
我并不完全相信这个名字......也许像Object.isLiteral这样的东西会更好。
It can cause problem with host objects, though, but I don't have a test ready.
不过,它可能会导致主机对象出现问题,但我还没有准备好测试。
回答by Mark
Say you have some testvarand want to see if it is an object, but not an array or null (these are both of type Object). You can do the following
假设你有一些testvar并且想看看它是否是一个对象,而不是一个数组或空值(这些都是对象类型)。您可以执行以下操作
testVar instanceof Object && !Array.isArray(testVar) && testVar !== null
回答by Ryan Taylor
If you use obj instanceof Objector typeof obj === "object"you get false positives on things like new Number(3)and arrays ([1,2,3]).
如果您使用obj instanceof Object或typeof obj === "object"在诸如new Number(3)和 数组 ( [1,2,3]) 之类的东西上得到误报。
Using o.constructor === Objectis 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. Conceptually it gives a valid, normal, undecorated object. We check for this case with Object.getPrototypeOf(o) === nullwhich will only hold true for the above undecorated object type.
使用o.constructor === Object很棒,但是有一个奇怪的边缘情况Object.create(null)– 事实上,它确实为您提供了一个普通对象,尽管不是以“正常”方式创建的。从概念上讲,它给出了一个有效的、正常的、未修饰的对象。我们检查这种情况,Object.getPrototypeOf(o) === null它仅适用于上述未修饰的对象类型。
The !!oconverts nullor undefinedto false. People were complaining about it above, and honestly o && ...is more succinct and unless you're serializing it doesn't matter. Nevertheless, I included it.
该!!o转换null或undefined到false。人们在上面抱怨它,老实说o && ...更简洁,除非你正在连载它并不重要。尽管如此,我还是把它包括了。
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)
}
回答by Lucas Tettamanti
const isObject = (x) => {
return Object.prototype.toString.call(x) == "[object Object]";
}
That works for me.
这对我行得通。
回答by bhdrk
Vanilla Javascript version of JQuery.isPlainObjectfunction.
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
回答by Conrad Damon
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]';
回答by Ehsan
Well, you don't need to check everything by yourself or write your own codes, when there are good libraries such as Lodashand Underscore.
好了,你不需要自己检查一切,或写自己的代码,当有好的库,如Lodash和下划线。
In Lodash, you can easily check it by isPlainObject function, e.g.:
在 Lodash 中,您可以通过 isPlainObject 函数轻松检查它,例如:
_.isPlainObject({'a': 12});
Check this page: https://lodash.com/docs#isPlainObject
回答by GullerYA
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 farfrom 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 - nullis a valid object as well, therefore the above will return true on nulltoo.
Personally, when really need to check if an expected variable is 'workable' object I'm always using this boringly repeated formula:
数组也是对象,因此对于数组也是如此。此外 -null也是一个有效的对象,因此上面的内容也将返回 true null。就个人而言,当真的需要检查预期变量是否是“可行”对象时,我总是使用这个无聊重复的公式:
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. 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.
最后但并非最不重要的 :) 请拜托,帮自己一个忙,不要将任何库用于如此简单的事情。Javascript 是一种快速发展的语言,今天的发展速度比昨天要快得多,以至于大多数库甚至都不够快,无法获取。除此之外,从事规范工作的人做得很好,而且大多数本地 API 都是干净、正确的,完全有意义并且与语言的其余部分保持一致。

