• Welcome to the world's largest Chinese hacker forum

    Welcome to the world's largest Chinese hacker forum, our forum registration is open! You can now register for technical communication with us, this is a free and open to the world of the BBS, we founded the purpose for the study of network security, please don't release business of black/grey, or on the BBS posts, to seek help hacker if violations, we will permanently frozen your IP and account, thank you for your cooperation. Hacker attack and defense cracking or network Security

    business please click here: Creation Security  From CNHACKTEAM

JS的类型转换 强制转换和隐式转换


Recommended Posts

强制转换

使用强制类型转换(type casting)处理转换值的类型。使用强制类型转换可以访问特定的值,即使它是另一种类型的。
ECMAScript中可用的3种强制类型转换如下:

[title-plane title=”3种强制转换类型”]Boolean(value) —— 把给定的值转换成Boolean型;
Number(value) —— 把给定的值转换成数字(可以是整数或浮点数);
String(value)     —— 把给定的值转换成字符串。[/title-plane]

输入

Copy
 
var str=123;
 
var str1='123';
 
console.log(typeof str);
 
console.log(typeof str1);
 
console.log(typeof String(str));
 
console.log(typeof Number(str1));
 
console.log(typeof Boolean(str1));
 

输出

Copy
 
number
 
string
 
string
 
number
 
boolean
 

隐式转换

JavaScript的数据类型分为六种,分别为null,undefined,boolean,string,number,object

object是引用类型,其它的五种是基本类型或者是原始类型

我们可以用typeof方法打印来某个是属于哪个类型的。不同类型的变量比较要先转类型,叫做类型转换,类型转换也叫隐式转换

隐式转换通常发生在运算符加减乘除,等于,还有小于,大于等

Copy
 
console.log(typeof '11') //输出string
 
console.log(typeog 11) //输出number
 
console.log('11' < 4 ) //输出fals
 
  1. 字符串加数字,数字就会转成字符串。
  2. 数字减字符串,字符串转成数字。如果字符串不是纯数字就会转成NaN。字符串减数字也一样。两个字符串相减也先转成数字。
  3. 乘,除,大于,小于跟减的转换也是一样。

隐式转换的其他例子

Copy
 
console.log(10+'20') //输出1020 string
 
console.log(10-'20') //输出-10 number
 
console.log(10-'one') //输出NaN not a number
 
console.log(10-'101a') //输出NaN
 
console.log(10*'20') //输出200 number
 
console.log('10'*'20') //输出200 number
 
console.log(20/'10') //输出2 number
 
console.log('20'/'10') //输出2 number
 
console.log('20'/'one') //输出NaN
 

[title-plane title=”关于 == “]

1.undefined等于null。

2.字符串和数字比较时,字符串转数字。

3.数字和布尔比较时,布尔转数字。

4.字符串和布尔比较时,两者转数字。

[/title-plane]

Copy
 
console.log(undefined==null) //true
 
console.log('0'==0) //true 字符串转数字
 
console.log(0==false) //true 布尔转数字
 
console.log('0'==false) //true 2个都转成数字
 
console.log(null==false) //false
 
console.log(undefined==false) //false
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now