检测数据类型
1. 在运算过程中,有的数据不是自己写的
2. 有可能在通过运算得到的,有可能是别人给的
3. 为了保证程序的正确运行,我们需要检测数据变量
关键字 typeof
两种用法:
1. typeof 变量
=> 语法: typeof 要检测的变量
=> 返回值(结果):以字符串的形式给你变量数据类型
var n1 = 100
//使用 typeof 关键字 去检测 n1 的变量
//把结果赋值给 res
var res = typeof n1
console.log(res)
//返回 number n1存的数值类型
2.typeof (变量)
=> 语法: typeof(要检测的变量)
=> 返回值:以字符串的形式给你变量数据类型
var s1 = '100'
//使用 typeof 关键字 去检测 n1 的变量
//把结果赋值给 res
var res2 = typeof (s1)
console.log(res2)
//返回 string
两种语法的区别
- typeof 只能检测紧跟的一个变量
//需求: 计算100+200 的结果的数据类型
var n1 = 100
var n2 = 200
//先运算typeof n1
//用 typeof n1 的结果去和 n2 进行加法运算
var res = typeof n1 + n2
console.log(res)
//返回 number200
2.typeof() 先运算小括号里面的结果,然后使用 typeof 去检测结果的数据类型
//需求: 计算100+200 的结果的数据类型
var n1 = 100
var n2 = 200
//先运算 100 + 200
//然后用 typeof 去检测 300 的数据类型
var res2 = typeof(n1 + n2)
//返回 number
3.只有 一个 var 赋值时 用哪个都一样
typeof 的返回值
=> 注意: typeof 的返回值是一个 字符串
=> 当两个 及 以上typeof 连用的时候,一定得到 string
=> 只能准确的检测基本数据类型
-> 数值: number
-> 字符串: string
-> 布尔: boolean
-> undefined: undefined
-> null: object
// 2. typeof 连用
var n1 = 100
//从右向左进行运算
//先计算2号检测n1的结果 number
//再计算1号检测2号返回的结果 string
// 1 2
var res = typeof typeof n1
console .1og(res)
// 3. typeof 的几种返回值
console.log(typeof 100) //返回值 number
console.log(typeof ' 100' ) //返回值 string
console.log(typeof true ) //返回值 boolean
console.log(typeof undefined) //返回值 undefined 注意:不是空是字符串
console log(typeof null) //返回值 object