不积小流无以成江海 ,夯实基础很重要,此次从js的数据类型开始,我相信会带来帮助。
简单数据类型:Number,String,Boolean,Null,Undefined
复杂数据类型:Array,Object
es6新增:Symbol
注意 : typeof()返回的都是字符串形式
alert(typeof b == "string") //true
string:字符串类型
number:数字类型,包括整形,浮点型,NaN
function:function
object:数组,对象,null
boolean:true,false
undefined:undefined
a).显式转换
利用js提供的函数parseInt() , parseFloat() , Number() , Boolean() , String()进行数据转换
1.parseInt()
//parseInt()
var a = "2312";
var b = "12.365";
var c = "yuci";
console.log(parseInt(a)); //2312
console.log(parseInt(b)); //12
console.log(parseInt(c)); //NaN
console.log(parseInt("10")); //返回 10
console.log(parseInt("19",10)); //返回 19 (10+9)
console.log(parseInt("11",2)); //返回 3 (2+1)
console.log(parseInt("17",8)); //返回 15 (8+7)
console.log(parseInt("1f",16)); //返回 31 (16+15)
console.log(parseInt("010")); //未定:返回 10
console.log(parseInt("+123")); //123
console.log(parseInt([1,2,4])); //1
console.log(parseInt("")); //NaN
2.Number()
2.1) 如果转换的内容本身就是一个数值类型的字符串,那么将来在转换的时候会返回自己。
2.2) 如果要转换的内容是空的字符串,那以转换的结果是0.
2.3) 如果是其它的字符,那么将来在转换的时候结果是NaN.
console.log(Number("123")); //123
console.log(Number("hello world")); //NaN
console.log(Number("")); //0
console.log(Number([])); //0
console.log(Number([1])); //1
console.log(Number([1,2])); //NaN
console.log(Number(null)); //0
console.log(Number(new Object())); //NaN
3.Boolean()
//Boolean()
var d = 123; //true
var e = false; //false
var f = ""; //false
var g = 0; //false
var h = null; //false
var i = undefined; //false
var j = NaN; //false
var k ={}; //true
var l = []; //true
console.log(Boolean(d));
console.log(Boolean(e));
console.log(Boolean(f));
console.log(Boolean(g));
console.log(Boolean(h));
console.log(Boolean(i));
console.log(Boolean(j));
console.log(Boolean(k));
console.log(Boolean(l));
数据类型
|
转换为true的值
|
转换为false的值
|
Boolean
|
true
|
false
|
String
|
任何非空字符串
|
""空字符串
|
Number
|
任何非零数字值
|
0和NaN
|
Object
|
任何对象
|
null
|
Undefined
|
/
|
undefined
|
4.String()
undefined,null不能用toString()
//String()
var number = 10;
console.log(number.toString()); //"10"
console.log(number.toString(2)); //"1010"
console.log(number.toString(8)); //"12"
console.log(number.toString(10)); //"10"
console.log(number.toString(16)); //"A"
console.log(String(null)); //"null"
var str = null;
console.log(str.toString()); //Cannot read property 'toString' of null
var number1;
console.log(String(number1)); //undefined
console.log(undefined.toString()); //Cannot read property 'toString' of undefined
var num = "123";
var num2 = 126;
console.log(+num); //123
console.log(num+num2); //"123126"
console.log(num2-num); //123-123=3
console.log(num2*num); //15498
console.log(num2/num); //1.024390243902439
console.log(num2%num); //3
console.log(num2>num); //true
var number = 1;
console.log(!!number); //true