如何检查变量是否是函数Number()或函数String() js的类型
How to check if variable is of type function Number() or function String() js
如何测试变量是否等于function Number()
或function String()
?
我从一个类型被设置为属性的模式定义中读取一个react prop。因此,一个有this.props.fieldType
是一个function Number()
或function String()
。
I have try:
if(this.props.fieldType instanceof Number)
和
if(Object.getPrototypeOf(this.props.fieldType) === Number.prototype)
根据Instanceof描述,但这不起作用。不知道为什么
尝试检查属性的值是否为
function Number()
或function String()
如果您的字面意思是函数 Number
或String
,请使用==
(或===
):
if (this.props.fieldType === Number) {
如果您的意思是"它是一个数字"或"它是一个字符串",请使用typeof
,而不是instanceof
:
if (typeof this.props.fieldType === "number") {
如果你的意思是"它是通过新的Number
创建的对象"(这将是非常不寻常的),那么instanceof
就是你想要的:
if (this.props.fieldType instanceof Number) {
以上三个例子:
var props = {
numberFunction: Number,
number: 42,
numberObject: new Number(42)
};
console.log(props.numberFunction === Number);
console.log(typeof props.number === "number");
console.log(props.numberObject instanceof Number);
你提到了instanceof
与getPrototypeOf
和相等比较的关系。重要的是要理解这是非常不同的事情。
instanceof
检查对象(左操作数)是否在其原型链中的任何位置具有函数(右操作数)的当前prototype
属性。它可能不是对象的直接原型;可能还会再往下。例如:
function Thing() {
}
var t = new Thing();
// The following is true, Object.prototype is in t's prototype chain
console.log(t instanceof Object);
// The following is false, t's prototype isn't Object.prototype;
// Object.prototype is further down t's prototype chain
console.log(Object.getPrototypeOf(t) === Object.prototype);
相关文章:
- 如何将参数应用于String.prototype.format函数
- 使用构造函数创建的数字没有其值作为属性,请取消String与构造函数的链接
- JS中的Shift Cipher(ROT-13)函数和String.fromCharCode的问题
- 使用string.format,最佳方法和替代方案在服务器端创建javascript函数
- 从回调函数中向 String.replace 返回一个值
- JavaScript String.replace:如何知道上次调用回调函数
- 是什么导致了错误“string.split 不是一个函数”
- RegExp的exec()函数和String的match()函数有什么区别
- JSP将带有XML字符的String属性传递给JavaScript函数不起作用
- 快速-试图模仿控制器.Get Router.use()需要回调函数,但出现了[object String]错误
- Backbone.js打印“;函数String(){〔本机代码〕}"而不是模型属性
- 为什么typeof Object、String、Number-Javascript中的一个函数
- 如何在原生String原型函数中使用jQuery
- Javascript:有没有可能有一个函数在Object/String..创建
- Javascript - V8中添加到String.prototype的函数性能很差
- 如何检查变量是否是函数Number()或函数String() js的类型
- 饮而尽.src TypeError: string不是函数
- String.split()返回额外的项(函数)
- “string.match()“;不是一个函数
- 将函数"String()"与函数参数一起使用的目的是什么