如何检查参数是否是JavaScript中的对象(而不是数组) [英] How to check if an argument is an object (and not an array) in JavaScript

查看:102
本文介绍了如何检查参数是否是JavaScript中的对象(而不是数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在测试 instasnceof 之后,我发现如果参数是数组或对象文字,它将返回true。

After testing out instasnceof I found that it will return true if the argument is an array or an object literal.

function test(options){
  if(options instanceof Object){alert('yes')}//this will alert for both arrays and object literals
}
test({x:11})// alerts
test([11])// alerts as well but I do not want it to

有没有办法测试参数options是否为对象文字?

Is there a way to test if the argument "options" is an object literal?

PS我正在创建一个允许用户访问其配置选项的模块,我想测试参数是否只是对象文字

P.S. I am creating a module that will allow the user to access its configuration options, and I want to test if the argument is only an object literal or not?

推荐答案


有没有办法测试参数options是否是对象文字?

is there a way to test if the argument "options" is an object literal?

不,因为没有意义。您可以测试它是否是对象,但它是如何创建的(通过函数调用中的文字,通过其他地方的文字,通过 new Object ,通过反序列化JSON字符串,...)不是维护的信息。

No, because it makes no sense. You can test whether it's an object, but how it was created (via a literal in the call to your function, via a literal elsewhere, through new Object, by deserializing a JSON string, ...) is not information that's maintained.


在测试出instasnceof后我发现它会如果参数是数组或对象文字,则返回true

after testing out instasnceof i found that it will return true if the argument is an array or an object literal

正确。 JavaScript中的数组是对象(和不是真正的数组)。

Correct. Arrays in JavaScript are objects (and not really arrays).

如果你想测试一个对象是一个普通的旧对象,你可以这样做:

If you want to test that an object is a plain old object, you can do this:

if (Object.prototype.toString.call(options) === "[object Object]") {
    // It's a plain object
}

但实际上没有理由这样做。这不是你的问题。只要他们传递的内容具有您期望的属性,就不要试图进一步限制对象。

But there's really no reason to do that. It's not your problem. As long as what they pass you has the properties you expect, don't try to limit the object further.


p.s。我正在制作一个模块,允许用户传递配置选项,我想测试以确保参数只是一个对象文字。

p.s. i'm making a module that will allow the user to pass it configuration options and i want to test to make sure that the argument is only an object literal.

为什么?如果用户想要使用尚未被声明为文字的对象,那么,你为什么要关心?如果他们想要使用他们通过不同构造函数创建的对象(例如,而不仅仅是普通对象),那么为什么还要关心?

Why? If the user wants to use an object that hasn't been declared as a literal right there and then, why would you care? If they want to use an object that they've created via a different constructor function (e.g., rather than just a plain object), again, why would you care?

这篇关于如何检查参数是否是JavaScript中的对象(而不是数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆