判断和转换JS中的数据类型

161 阅读4分钟

判断和转换JS中的数据类型

判断JS中的数据类型

1. typeof

typeof是一个操作符,其右侧跟一个一元表达式,并返回这个表达式的数据类型。返回的结果用该类型的字符串(全小写字母)形式表示,可以判断出来null类型之外的原始数据类型

原始数据类型包括:undefined,boolean,null,string,symbol,number

<script>
    typeof '1'          //string
    typeof 1            //number
    typeof null         //object
    typeof undefined    //undefined
    typeof symbol()     //symbol
    typeof {};          //object
    typeof function(){} //function
    typeof []           //object
    typeof new Data()   //object
    typeof new RegExp() //object
</script>

typeof判断数据类型的问题:

问题一:typeof不可以识别null,如何识别null?

如果我们想要判断数据类型是否为null,可以直接使用===全等运算符判断

<script>
    let a = null
    typeof a    //object
    a === null  //true
</script>

问题二:typeof作用于未定义的变量,会返回undefined

<script>
    let a 
    typeof a //undefined
</script>

问题三:typeof Number(1)的返回值number

当Number和String作为普通函数调用时,等价于将参数转化为响应的原始数据类型。相当于做了一个强制数据类型转换的操作,而不是当作构造函数。注意与Array区分,因为Array()等价于new Array()。

<script>
    typeof Number(1)             //number
    typeof String(1)             //string
    let arr = Array(1,2,3)       //[1,2,3]
    let arr1 = new Array(1,2,3)  //[1,2,3]
</script>

问题四:typeof new Number(1)的返回值为object

<script>
    typeof new Number(1)             //object
    typeof new String(1)             //object
</script>

2. instanceof

instanceof用来判断A是否为B的实例。

语法:A instanceof B

其中如果A是B的实例,则返回true,否则返回false。

instanceof检测的是原型,内部机制是通过判断对象的原型链中是否有类型的原型。

<script>
{} instanceof Object; //true
[] instanceof Array;  //true
[] instanceof Object; //true
let str = new String(123)
str instanceof String; //true

"123" instanceof String; //false
1 instanceof Number      //false
true instanceof Boolean  //false
</script>

注意:instanceof方法不能用来判断原始数据类型的数据,可以用来判断对象的类型。同时instanceof并不是完全准确的,因为在ECMAScript7中可以通过自定义symbol.haslnstance方法来掩盖默认行为。

3. constructor

当一个函数F被定义时,JS引擎会为F添加prototype原型对象,然后在prototype上添加一个constructor属性,并让其指向F的引用,F利用原型对象的constructor属性引用了自身,当F作为构造函数创建对象时,原型上的constructor属性被遗传到了新创建的对象上,从原型链角度讲,构造函数F就是新对象的类型。这样做的意义是,让对象诞生以后,就具有可追溯的数据类型。

    <script>
        let str = ''
        console.log(str.constructor === String); //true
        
        let num = 1
        console.log(num.constructor === Number); //true
        
        let boo = true
        console.log(boo.constructor === Boolean);//true

        let obj = new Object()
        console.log(obj.constructor == Object);//true
    </script>

4. Object.prototype.toString()

toString()是Object的原型方法,调用该方法,默认返回当前对象的[[Class]]。这是一个内部属性,其格式为[object Xxx],其中Xxx就是对象的类型。

  对于Object对象,直接调用toString()就能返回[object Object],而对于其他对象,则需要通过call、apply来调用才能返回正确的类型信息。

<script>
    let obj = new Object()
    console.log(obj.toString());//[object,Objec]
    
    Object.prototype.toString({a:1})    //[object,Objec]
    Object.prototype.toString.call('')  //[object,String]
    Object.prototype.toString.call(1)  //[object,Number]
    Object.prototype.toString.call(null)  //[object,Null]
    Object.prototype.toString.call(undefined)  //[object,undefined]
</script>

5. isArray

Array.isArray(val) 用来判断val是否是一个数组,如果是返回true,如果不是返回false

<script>
    Array.isArray([])  //true
    Array.isArray({})  //false
    
    ;(function(a,b,c){
        console.log(Array.isArray(arguments))//false
    }(1,2,3))
</script>

arguments:它是函数运行时的实参列表,本质是对象但是长得像数组

JS中数据类型的转换

强制转换

转化为字符串类型:toString(),String()

toString()方法:不可以转换undefined和null

//toString()方法
//
let num = 1
let boo = true
let und = undefind
console.log(typeof num.toString()) //string
console.log(typeof boo.toString()) //string
//console.log(typeof und.toString()) //报错


//String()方法
let nul = null
console.log(typeof String(und)) //string
console.log(typeof String(nul)) //string

转化为数字类型:Number(),parseInt(),parseFloat()

1.Number()可以把任意值转换成数值,如果要转换的字符串中有一个不是数值的字符,返回NaN > 2.parseInt(),parseFloat()如果解析的第一个字符不为数字则会结束解析返回NaN

//Number()
let str = '123'
let str2 = '1x1'
console.log(typeof Number(str)) //number
console.log( Number(str2)) // NaN

//parseInt():转化为整数
let a = '12.3px'
console.log(parseInt(a)) //12

//parseFloat():会把字符串转会为浮点数
let b = '13.3.4'
console.log(parseFloat(a))//12.3
console.log(parseFloat(b))//13.3

转化为布尔类型:Boolean()

Boolean()转化0,'',NaN,undefined,null都会转化为false,其他的都为true

//Boolean()
console.log(Boolean(1)) //true
console.log(Boolean(0)) //false
console.log(Boolean('1')) //true
console.log(Boolean('')) //false

隐式转换

string隐式转换

拼接字符串:任意数据类型拼接上一个字符串类型的数据都会被转化为字符串类型

let str = 1+'11'
console.log(str)   //111
console.log(typeof str)  //string

number隐式转换

计算:当任意类型数字通过*,/,-运算会被转化为数字类型

let a = '123'
console.log(a*1) //123 
console.log(a-0) //123
console.log(a/1) //123

boolean隐式转换 == === !if()

console.log(1===1) //true
console.log(1===2) //false
console.log(!0) //true

//if()
let a = 123
if(a){}
if括号中的内容为boolean值