数据类型转换

数据类型

基本数据类型

  • Number
  • String
  • Undefined
  • Boolean
  • Null

引用数据类型

  • Object

typeof

typeof两种书写形式

  • typeof(123)
  • typeof 123

typeof返回的值的数据类型为string
返回的值有:number、string、boolean、undefined、object、function

显示类型转换

  • Number(mix)
Number(null) //0 
Number(undefined) // NaN
Number("123abc") // NaN
Number([2])//2
Number([1,2])//NaN
Number({})//NaN
  • parseInt(string,redix)
//redix可有可无,redix存在则将当前数以redix为基底转为十进制 
parseInt(null)=>NaN
// 从第一个字符开始截取,第一个不是数字则返回NaN
parseInt(3,2)//NaN
parseInt(2,0)//2
  • parseFloat(string)
  • toString(radix) 不支持null和undefined,报错
    var demo = 123; 
    demo.toString()//"123"
    var num=3;
    num.toString(2)//"11"
    
    123.toString();//报错  点运算符优先级较高,会首先识别为浮点型而不会识别成函数调用
    
    document.write({})//[object,Object]
    //调用toString方法后打印到页面
    
    //toString方法
    //Object.prototype.toString
    
    var obj = {};obj.toString()//"[object,Object]"
    
    Object.prototype.toString.call({})//"[object,Object]"
    
    Object.prototype.toString.call(123)//"[object,Number]"
    
    Object.prototype.toString.call('123')//"[object,String]"
    
    Object.prototype.toString.call(true)//"[object,Boolean]"
    
    Object.prototype.toString.call([1,2,3])//"[object,Array]"
    
    
    //toString方法重写  ==> 转为字符串
    
    //Number.prototype.toString
    var num = 123;num.toString();//'123'
    
    //Array.prototype.toString
    [1,2,3].toString();//'1,2,3'
    
    //Boolean.prototype.toString
    true.toString();//'true'
    
    //String.prototype.toString
    '123'.toString();//"123"
    
  • String(mix)
  • Boolean()undefinednull0NaNfalse"" 这六个值外都是true

隐式类型转换

  • isNaN() = > Number()
  • ++/-- +/- (一元正负) = > Number()
  • + 加号运算符的数据如果出现字符串与对象,都会转成字符串
  • - * / % = > Number()
  • && || ! 隐式调用Boolean()方法,但&&和||返回的还是之前的值而不是Boolean()转过的Boolean值
  • < > <= >= 字符串跟数字比较调用Number(),字符串跟字符串比较ASCII值
  • == != undefined>0 =>false undefined<0 =>false undefined==0 =>false null>0 =>false null<0 =>false null==0 =>false undefined==null
  • 引用值比对的是地址 {}=={} ==> false
//加号运算符的数据如果出现字符串与对象,都会转成字符串先调用String方法再相加
var obj = {};
var arr = [];
var num = 12;
var fn = function(){};
console.log(obj+num)//"[object Object]12" 
console.log(arr+num)//"12"
console.log(obj+fn)//"[object Object]function(){}"
console.log(arr+fn)//"function(){}"
console.log([2] == 2)//true
console.log([2] !== 2)//true
逗号运算符

输出最后一位的运算结果

var a = (1,2)
console.log(a)//2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值