类型判断:
typeJudge() { //typeof 用来判断变量类型 var s: string = 'egret'; var isString: boolean = typeof s === 'string'; console.log(typeof s === 'string'); console.log(typeof s === 'number'); console.log(typeof s === 'any'); console.log(typeof s === 'array'); //instanceof 用来判断方法或者接口类型 var a: A = new A(); console.log(a instanceof A); console.log(a instanceof B); }
函数:
function area(shape: string, width: number, height: number) { var area = width * height; return "I'm a " + shape + " with an area of " + area + " cm squared.";}document.body.innerHTML = area("rectangle", 30, 15);console.log(document.body.innerHTML )
时间戳获取:
Javascript 获取当前时间戳(毫秒级别):第一种方法:var timestamp1 = Date.parse( new Date());结果:1470220594000第二种方法:var timestamp2 = ( new Date()).valueOf();结果:1470220608533第三种方法:var timestamp3 = new Date().getTime();结果:1470220608533第一种获取的时间戳是精确到秒,第二种和第三种是获取的时间戳精确到毫秒。获取指定时间的时间戳:new Date("2016-08-03 00:00:00");时间戳转化成时间:function timetrans(date){ var date = new Date(date*1000);//如果date为13位不需要乘1000 var Y = date.getFullYear() + '-'; var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' '; var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'; var m = (date.getMinutes() <10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'; var s = (date.getSeconds() <10 ? '0' + date.getSeconds() : date.getSeconds()); return Y+M+D+h+m+s;}
日期工具类:
dateTime.ts:formatDate(){ //三目运算符 const Dates = new Date(); //年份 const Year : number = Dates.getFullYear(); //月份下标是0-11 const Months : any = ( Dates.getMonth() + 1 ) < 10 ? '0' + (Dates.getMonth() + 1) : ( Dates.getMonth() + 1); //具体的天数 const Day : any = Dates.getDate() < 10 ? '0' + Dates.getDate() : Dates.getDate(); //小时 const Hours = Dates.getHours() < 10 ? '0' + Dates.getHours() : Dates.getHours(); //分钟 const Minutes = Dates.getMinutes() < 10 ? '0' + Dates.getMinutes() : Dates.getMinutes(); //秒 const Seconds = Dates.getSeconds() < 10 ? '0' + Dates.getSeconds() : Dates.getSeconds(); //返回数据格式 return Year + '-' + Months + '-' + Day + '-' + Hours + ':' + Minutes + ':' + Seconds; }
计时器工具类:
timer.tspublic timePromise : any;...timer( flag ){ //flag是一个标识,何时计时和何时停止 var second = 0; if( flag == 1){ this.timePromise = setInterval( (success)=>{ //回掉函数开始计时了 second++ ; //other actions },1000); } else if( flag == 0 ){ //other actions //清除计时器 window.clearInterval(this.timePromise); }}