JavaScript

js类型转换—实战篇

2019-08-24  本文已影响0人  Aniugel
显示转换
// 7种数据类型 
    // number string boolena null undefined  基本数据类型
    // object  引用数据类型 object、array、function
    // symbol 
    typeof ('1' - '1')//numner 
    typeof (a)//undefined
    typeof (typeof a)//string 数据类型返回值是字符串
    typeof (typeof 123)//string

    // 显示转换
    var a = null;
    console.log(typeof (Number(a) + '-' + Number(a)))// "0-0"   string
    var a = undefined;
    var a = 'la';
    console.log(typeof (Number(a) + '-' + Number(a)))// "NaN-NaN"   string
    var a = 'true';
    var a = 'null';
    var a = 'undefined';
    console.log(typeof (parseInt(a) + '-' + parseInt(a)))// "NaN-NaN"   string

    var a = 'b';
    // 0123456789abcdef 16进制
    console.log(parseInt(a, 16))//11 
    console.log(parseInt('123qwe'))// 123 数字在前只截前面的数据
    console.log(parseInt('123qwe123'))// 123
    console.log(parseInt('qwe123'))// NaN

    var str = null;
    var str = undefined;
    // console.log(str.toString()) //报错

    var str = '100';
    console.log(parseInt(str, 2))//4
    console.log(parseInt(str, 2).toString(16))//4


    console.log((100).toString())//100
    console.log((100.0).toString())//100
    console.log((10).toString(16))//a
    console.log((10).toString(2))//1010

    console.log(Boolean(null))//false
    // null undefined 0 NaN '' false  都是false  其他都是true
隐式转换
// 隐式转换
    var a = 'a' + 1
    console.log(a)//a1

    var a = '123'
    console.log(a++)//123
    console.log(a)//124

    var a = '123'
    console.log(++a)//124
    console.log(a)//124

    var a = '3' * 2 //* - / % str-->number
    console.log(a)//6

    console.log('2' > 1) //true str-->number
    console.log(2 > '1') // == != > < >= <=  str-->number
    console.log(1 != '2')
    console.log('a' > 'b') //false  ascii
    console.log(1 === '1') //不进行隐式转换
    console.log(NaN == NaN);//false 自己和自己不相等 

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

    console.log(undefined < 0)//false undefined-->NaN
    console.log(undefined > 0)//false
    console.log(undefined == 0)//false 
    console.log(undefined == NaN)//false 
    console.log(undefined == null)//true
    console.log(null == 0)//false
    console.log(Boolean(null) == 0)//true
    console.log(isNaN('123'))//false 隐式转换
    console.log(isNaN(123))//false
    console.log('undefined', isNaN(undefined))//true
    console.log('null', isNaN(null))//false  null-->0
    console.log(1 == !null)//true !null-->1


    console.log(false + 1)//1
    console.log(typeof (a) && (-true) + (+undefined) + '') //'NaN'
    //     undefined (str)  &&  -1     +     NaN   +     ''
    console.log(1 + 5 * '3' === 16)//true 1+15===16
    console.log(!!' ' + !!'' - !!false || 'abc')// true  1+0- 0 || 'abc'
    console.log(window.b || (window.b = '1'))//'1' 先算括号里的 所以第一步为true
上一篇下一篇

猜你喜欢

热点阅读