gpt4 book ai didi

javascript - js 如何检查变量的类型是 function Number() 还是 function String()

转载 作者:行者123 更新时间:2023-11-28 15:02:18 25 4
gpt4 key购买 nike

在 JavaScript 中。如何测试变量是否等于 function Number()function String()

我从模式定义中读取react prop,其类型设置为属性。因此,this.props.fieldType 是一个function Number()function String()

我已经尝试过:

 if(this.props.fieldType instanceof Number)

if(Object.getPrototypeOf(this.props.fieldType) === Number.prototype)

根据 instanceof description但这不起作用。不知道为什么。

最佳答案

trying to check if the property has a value of function Number() of function String()

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

if (this.props.fieldType === Number) {

如果您的意思是“它是数字”还是“它是字符串”,请使用 typeof,而不是 instanceof:

if (typeof this.props.fieldType === "number") {

如果您的意思是“它是通过 new 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 属性 在它的原型(prototype)链中。它可能不是对象的直接原型(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);

关于javascript - js 如何检查变量的类型是 function Number() 还是 function String(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40485975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com