day07 date、对象、定时器

date的声明

使用new关键词声明

new Date()
  • 无参构照声明

var date =new Date()
console.log(date)
  • 传入字符串作为参数(值超出自带向上递增)

var date =new Date("2020/2/14 19:05:00")
  • 传递多个number为参数

var date =new Date(2023,1,14,19,05,00)//2023/2/14 19:05:00,月份取值0-11

日期对象的相关方法

get开头 获取

var date = new Date()
console.log(date.getFullYear())//获取年
console.log(date.getMonth())//获取月(0-11)
console.log(date.getDate())//获取日
console.log(date.getDay())//获取星期几(0-6)
console.log(date.getHours())//获取小时(0-23)
console.log(date.getMinutes())//获取分钟(0-59)
console.log(date.getSecond())//获取秒(0-59)
console.log(date.getMillisecond())//获取毫秒(0-999)
console.log(date.getTime())//离隔离栏的毫秒值
console.log(date.toLocaleString())//根据本地格式转为字符串(可以进行格式化)
console.log(date.toLocaleDateStrin())根据本地格式转为日期字符串

set开头 设置

var date = new Date()
console.log(date.setFullYear())//获取年
console.log(date.setMonth())//获取月(0-11)
console.log(date.setDate())//获取日
console.log(date.setDay())//获取星期几(0-6)
console.log(date.setHours())//获取小时(0-23)
console.log(date.setMinutes())//获取分钟(0-59)
console.log(date.setSecond())//获取秒(0-59)

练习

设计一个函数返回两个时间间隔的天数

function fn(date1,date2){
    var ms=Math.abs(date1-date2)
    //将毫秒转为天数
    return parseInt(ms/1000/60/60/24)
}
console.log(fn(new Date(),new Date("2020/11/22")))

设计一个函数返回一个时间的日期,以YY-mm-NN hh:MM:ss格式显示

function Gettoday(date){
//得到当前的年月日
    return `${date.getFullYear()}-${fn(date.getMonth())+1}-${fn(date.getDate())} ${fn(date.getHours())}:${fn(date.getMinutes)}` 
}
console.log(Gettoday(new Date()))
//在小于10的前面添个0
function fn(number){
    if(number<10){
        return "0"+return
    }
    return number
}

对象

对象的声明(Object)

  • 赋值声明

var obj ={}//空对象
  • 以new关键词来调用构照函数声明(new Objeck)

var obj= new Object{}//空对象

对象的增删改查

var obj ={
    name:'李帅帅'//key为name ,值为李帅帅
    sex:"男"
}
console.log(obj.name)//通过对象名.属性名
console.log(obj["name"])//通过对象名[属性字符串]
obj.age= 18//对没有的属性进行赋值就是增加
obj.age="李好帅"//对原有的属性重新赋值
  • 删(delete)

delete obj.sex

this关键词

  • 对象函数中的this

//指向对应的函数
obj.Say=function (){
    console.log(this==obj)//true
}
obj.Say()
  • 函数中的this

function fn(){
    console.log(this)//指向Windows
}
fn()

Windows对象的两个函数

  • setInterval 定时器(一定时间内循环执行某个操作)

第1个为执行的代码,第2个为间隔的时间,第3个为第一个传递的参数
setInterval(function(arg){},2000,1)
var i =0
var timer = setInterval(function(arg){
    i++
    console.log(1)
    if(i==100){//当i为100时停止
        clearInterval(timer)//清除定时器
}
},2000,1)
  • setTimeout延时器(延迟执行某个操作 执行一次)

setTimeout(function(arg){},2000,1)
var timer =setInterval(function(arg){
    conso.log(1)
},2000)
clearTimeout(timerz)

setInterval及setTimeout是异步的,不会阻塞正常代码的执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值