number 和 Number in javascript 有什么区别?
What is the difference between number and Number in javascript?
输出:
var x = 5;
typeof (x) //will give number type as output
但是下面的代码 returns false:
var x = 5;
x instanceof Number; //will give false as output
谁能解释一下number和Number的区别。我如何让第二个工作?
how do I make the second one work?
instanceof
运算符检查给定变量是否是 class 的对象。根据 MDN 的定义,
The instanceof
operator tests whether the prototype
property of a constructor appears anywhere in the prototype chain of an object.
要使其工作,您需要使用 Number
class'(或其任何后代 class')构造函数实例化变量:
var x = new Number(5);
x instanceof Number // true
typeof(x)
始终是 returns 表示类型 x 所属的字符串。
instanceOf
运算符使用 prototype
属性 来标识实例是否属于 class。
x instanceof Number;
在你的例子中 returns false
因为 x
是一个 原始 并且永远不会 return true
。如果你确实希望它 return 为真,你可以 "wrap" 你的原语变成 Number
class 像这样:
new Number(x) instanceof Number; //will give TRUE as output
输出:
var x = 5;
typeof (x) //will give number type as output
但是下面的代码 returns false:
var x = 5;
x instanceof Number; //will give false as output
谁能解释一下number和Number的区别。我如何让第二个工作?
how do I make the second one work?
instanceof
运算符检查给定变量是否是 class 的对象。根据 MDN 的定义,
The
instanceof
operator tests whether theprototype
property of a constructor appears anywhere in the prototype chain of an object.
要使其工作,您需要使用 Number
class'(或其任何后代 class')构造函数实例化变量:
var x = new Number(5);
x instanceof Number // true
typeof(x)
始终是 returns 表示类型 x 所属的字符串。
instanceOf
运算符使用 prototype
属性 来标识实例是否属于 class。
x instanceof Number;
在你的例子中 returns false
因为 x
是一个 原始 并且永远不会 return true
。如果你确实希望它 return 为真,你可以 "wrap" 你的原语变成 Number
class 像这样:
new Number(x) instanceof Number; //will give TRUE as output