1.5 类型转换
类型
string
number
boolean
object
function
Object
Date
Array
null
undefined
typeof 操作符
typeof "John" // 返回 string
typeof 3.14 // 返回 number
typeof false // 返回 boolean
typeof [1,2,3,4] // 返回 object
typeof {name:'John', age:34} // 返回 object
typeof function () {} // 返回 function
typeof myCar // 返回 undefined (如果 myCar 没有声明)
typeof undefined // 返回 undefined
typeof null // 返回 object
constructor 属性
document.write([1,2,3,4].constructor) //function Array() { [native code] }
字符串 <=> 数字
var str = '1.23';
var a = Number(str);
var b = parseInt(str);
var c = parseFloat(str);
var num = 1.23;
var a = String(num);
var b = num.toString();
var c = num.toFixed(1);//指定小数位数
var d = num.toPrecision(2);//指定有效长度
Boolean <=> 字符串
var checked = true;
var a = String(checked);
var b = checked.toString();
var a = Boolean(true);
Boolean <=> 数字
var checked = true;
var a = Number(checked);
var a = Boolean(0);
日期 <=> 字符串
var date = new Date();
var a = String(date);
var b = date.toString();
var c = date.toUTCString();
var s ='2017-04-18 09:16:15';
var date = new Date(s );
console.log(date.toLocaleString());
日期 <=> 数字
var date = new Date();
var a = date.getTime();// 时间戳,毫秒数
var year = date.getYear();// 年
var month = date.getMonth();// 月
var day = date.getDate();// 日
var date = new Date(1000);// 毫秒数
不同类型运算处理
- 自动转换处理;(一般情况 字符串 > 数字 > 其他)