早睡早起,方能养生!
Sleep early rise early, way to keep healthy!

JavaScript如何判断变量是否为数字类型,字符类型?

super
2021-11-10 19:22
views 342

使用typeof运算符判断

 

  1. 写法1:typeof  变量

 

let val = 1;
alert(typeof val); // number

 

let val = 'my name is pipi!';
alert(typeof val); // string

 

let val = 1.23;
alert(typeof val); // number

 

let val = true;
alert(typeof val); // boolean

 

let val = null;
alert(typeof val); // object

 

// let val = 1;
alert(typeof val); // undefined

 

写法2:typeof(表达式)

 

alert(typeof(1 + 2)); // number

 

alert(typeof(1 + '个')); // string

 

let val = true;
alert(typeof(val ? 1 : 'string 1')); // number

 

let val = false;
alert(typeof(val ? 1 : 'string 1')); // string

 

let val = function(){}
alert(typeof(val)); // function

 

let val = new Date();
alert(typeof(val)); // object


分享
0 条讨论
top