js中数据类型装换
### 显示数据类型的转换
- typeof:能防回六中操作类型的数据:Number, String, Boolean, Objecet, undefined, function
~JavaScript~
var a = 1;
//conloe.log(typeof(a)) 值为Number
var a = [];
//conloe.log(typeof(a)) 值为Object
var a = {};
//conloe.log(typeof(a)) 值为Object
var a = null;
//conloe.log(typeof(a)) 值为Object
var a = true;
//conloe.log(typeof(a)) 值为Boolean
var d;
//conloe.log(typeof(b)) 值为Undefined
var a = function(){};
//conloe.log(typeof(a)) 值为function
- js中默认存在一定的类型装换, 默认情况下js会对字符串进行一些隐式转换
~~~JavaScript
console.log("1" + 1) //11
console.log("1" + "1") //11
console.log("1" * 1) //1
console.log("1" -1) //0
console.log("2" + 1) //21
console.log("2"- 1) //1
~~~ - Number(‘number‘)//把里面的东西转换为数字
var demo = '123'
demo = Number(demo) //把demo装换为数字
console.log(typeof(demo)) //number
var demoB = true
console.log(Number(demoB)) //1 boolean值转为数字类型以后1为真, 0为假
console.log(Number("sfjafja")) //NaN 不能转为为数字的值转换为数字后, 值为NaN
var demoN = null
console.log(Number(demoN)) //值为0
var demoun = undefined
console.log(Number(demoun)) //NaN
- parseInt():
parseInt(val, radix) 把里面的数字转换为整型, 第一个参数可以使字符串, Boolean, 甚至对象,函数,
第二个参数为进制数,默认把该数值当成该进制的数,然后以该进制为基地转换为10进制的数
重新理一下: 就是把传进来的val当成 radix进制, 然后把他转换为10进制,默认不传值的话是10进制
~~javascript~~
var i = ‘123‘
console.log(parseInt(i), typeof(parseInt(i))) //123 number
var i = "123.9"
console.log(parseInt(i), typeof(parseInt(i))) //123 number
var demoi = false
console.log(parseInt(demoi), typeof(parseInt(demoi))) //NaN number
var demor = 3
console.log(parseInt(demor, 2)) // NaN , 默认把3当成2进制的数,由于2进制中不存在3, 所以输出为NaN
var demorx = ‘b‘
console.log(parseInt(demorx, 16)) //11 ,把b当成16进制数,然后把它转换为10进制数
var demos = ‘100px‘
console.log(parseInt(demos)) //100 parseInt会从开头的数字开始看,看完不是数字为值
var demols = "afaf100fafa"
console.log(parseInt(demols)) // NaN
- parseFloat(): parseFloat(‘number‘) //用法和parseInt差不多,但是会把所有的数值都转换为浮点数
console.log(parseFloat("100")) //100 整数的时候parseFloat是不会添加.0 de console.log(parseFloat("100.1")) //100.1 console.log(parseFloat('100.0.01')) //100 默认只会取一个小数点 console.log(parseFloat('100.12raga')) //100.12
- toString(‘mix‘) //转换为字符串
var demot = 1213
var demots = toString(demot)
var demounde = toString(undefined)
console.log(typeof (demounde)) //string
console.log(typeof(demots)) //string
- .toString(radix)
想把谁转换为字符串就后面.tostring undefined 和 null 不能用 toString
可以把数字转换成该目标进制的字符串, 以十进制为基地转化成目标进制
注意区别于parseInt(val, radix) 他是把val当成radix进制,然后转换为10进制
~~~~javascript
console.log(typeof(demot.toString()))
var demo = 123
console.log(demo.toString(8), typeof demo.toString(8)) //173 string
~~~~
原文地址:https://www.cnblogs.com/ghostdot/p/11370844.html
时间: 2024-10-12 20:21:07