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

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

问题描述

在测试 instanceof 之后,我发现如果参数是数组或对象文字,它将返回 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?

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

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?

不,因为它没有意义.您可以测试它是否是 object,但是它是如何创建的(通过调用函数中的文字,通过其他地方的文字,通过 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. 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天全站免登陆