其他进制的数字
在js中,如果需要表示16进制的数字,则需要以0x开头
如果需要表示8进制的数字,则需要以0开头
如果要要表示2进制的数字,则需要以0b开头,但是不是所有的浏览器都支持
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>其他进制的数字</title>
<script type="text/javascript">
var a = 123;
/*
在js中,如果需要表示16进制的数字,则需要以0x开头
如果需要表示8进制的数字,则需要以0开头
如果要要表示2进制的数字,则需要以0b开头,但是不是所有的浏览器都支持
*/
//十六进制
a = 0x10;
a = 0xff;
a = 0xCafe;
//八进制数字
a = 070;
//二进制数字
//a = 0b10;
//像"070"这种字符串,有些浏览器会当成8进制解析,有些会当成10进制解析
a = "070";
// a = parseInt(a);
//可以在parseInt()中传递一个第二个参数,来指定数字的进制
a = parseInt(a,10);
console.log(typeof a);
console.log(a);
</script>
</head>
<body>
</body>
</html>
与或运算
&& || 非布尔值的情况
- 对于非布尔值进行与或运算时,会先将其转换为布尔值,然后再运算,并且返回原值
- 与运算:
- 如果第一个值为true,则必然返回第二个值
- 如果第一个值为false,则直接返回第一个值
- 或运算
- 如果第一个值为true,则直接返回第一个值
- 如果第一个值为false,则返回第二个值
- 如果第一个和第二个都不是true,则返回第二个值
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>与或运算</title>
<script type="text/javascript">
/*
&& || 非布尔值的情况
- 对于非布尔值进行与或运算时,会先将其转换为布尔值,然后再运算,并且返回原值
- 与运算:
- 如果第一个值为true,则必然返回第二个值
- 如果第一个值为false,则直接返回第一个值
- 或运算
- 如果第一个值为true,则直接返回第一个值
- 如果第一个值为false,则返回第二个值
- 如果第一个和第二个都不是true,则返回第二个值
*/
//true && true
//与运算:如果两个值都为true,则返回后边的
var result = 2 && 1;
//与运算:如果两个值中有false,则返回靠前的false
//false && true
result = 0 && 2;
result = 2 && 0;
//false && false
result = NaN && 0;
result = 0 && NaN;
//true || true
//如果第一个值为true,则直接返回第一个值
result = 2 || 1;
result = 2 || NaN;
result = 2 || 0;
//如果第一个值为false,则直接返回第二个值
result = NaN || 1;
result = NaN || 0;
result = "" || "hello";
result = -1 || "你好";
console.log("result = "+result);
</script>
</head>
<body>
</body>
</html>
转换为Boolean
将其他的数据类型转换为Boolean
使用Boolean()函数
- 数字 ---> 布尔
- 除了0和NaN,其余的都是true
- 字符串 ---> 布尔
- 除了空串,其余的都是true
- null和undefined都会转换为false
- 对象也会转换为true
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>转换为Boolean</title>
<script type="text/javascript">
/*
将其他的数据类型转换为Boolean
使用Boolean()函数
- 数字 ---> 布尔
- 除了0和NaN,其余的都是true
- 字符串 ---> 布尔
- 除了空串,其余的都是true
- null和undefined都会转换为false
- 对象也会转换为true
*/
var a = 123; //true
a = -123; //true
a = 0; //false
a = Infinity; //true
a = NaN; //false
//调用Boolean()函数来将a转换为布尔值
a = Boolean(a);
a = "hello";//true
a = "true";//true
a = "false";//true
a = "错误";//true
a = " ";//true
a = "";//false
a = Boolean(a);
a = null; //false
a = Boolean(a);
a = undefined; //false
a = Boolean(a);
a = window; //true
a = Boolean(a);
console.log(typeof a);
console.log(a);
</script>
</head>
<body>
</body>
</html>