如何检查变量是否是函数Number()或函数String() js的类型

How to check if variable is of type function Number() or function String() js

本文关键字:函数 String js 类型 Number 是否是 何检查 检查 变量      更新时间:2023-09-26

如何测试变量是否等于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()

如果您的字面意思是函数 NumberString,请使用==(或===):

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);


你提到了instanceofgetPrototypeOf和相等比较的关系。重要的是要理解这是非常不同的事情。

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);