目录
一、相等和等同运算符
内核会转换为相同类型的对象进行比较
1、相等运算符
不管数据是什么类型的,只判断值是否相等
<script>
var item1 = 1;
var item2 = '1';
if(item1 == item2){
console.log("They are Same");
}else{
console.log("They are not same");
}
</script>
2、等同运算符
判断值和类型是否都相同
<script>
var item1 = 1;
var item2 = '1';
if(item1 === item2){
console.log("They are Same");
}else{
console.log("They are not same");
}
</script>
3、对象的相等与等同
引用的比较
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var s1 = {
name:"Jame",
age:12
}
var s2 = {
name:"Jame",
age:12
}
var s3 = s2;
var test1 = s1 == s2;
var test2 = s2 == s3;
var test3 = s1 === s2;
var test4 = s2 === s3;
console.log("test1:" + test1);
console.log("test2:" + test2);
console.log("test3:" + test3);
console.log("test4:" + test4);
</script>
</body>
</html>
二、显式类型转换
1、将数值转换为字符串toString()
常用的转换方法
方法 | 说明 | 返回 |
toString() | 十进制形式 | 字符串 |
toString(2/8/16) | 二进制、八进制、十六进制形式 | 字符串 |
toFix(n) | 保留n位小数 | 字符串 |
toExponential(n) | 用指数表示法表示数值,小数点前有1位后有n位 | 字符串 |
toPrecision() | n位有效数字表示 数值 | 字符串 |
<script>
var num = 10;
var numString = num.toString();
</script>
2、将字符串转换为数值
常用转换方法
函数 | 说明 |
Number() | 生成整数或实数 |
parseInt() | 生成整数 |
parseFloat() | 生成实数 |
var numString = "10";
var num = numString.Number();
3.类型转换实例
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<script>
var myString = "56.02 degrees centigrade";
var myInt;
var myFloat;
document.write("\"" + myString + "\" is " + parseInt(myString, 10) +
" as an integer" + "<br/>");
myInt = parseInt(myString, 10);
document.write("\"" + myString +
"\" when converted to an integer equals " + myInt + "<br/>");
myFloat = parseFloat(myString);
document.write("\"" + myString +
"\" when converted to a floating point number equals " + myFloat);
</script>
</body>
</html>
华氏度转摄氏度
<!DOCTYPE html>
<html lang="en">
<head>
<title>/title>
</head>
<body>
<script>
// Equation is °C = 5/9 (°F - 32).
var degFahren = prompt("Enter the degrees in Fahrenheit",50);
var degCent;
degCent = 5/9 * (degFahren - 32);
alert(degFahren + "\xB0 Fahrenheit is " + degCent + "\xB0 centigrade");
</script>
</body>
</html>