try-catch,Error,Date,Date-API

try-catch

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 一旦遇到程序报错,后面的代码就都不执行了(致命性错误)
        // obj.name = 'zhangsan'
        // console.log(123)

        try{
            // 如果这里的代码没有报错就不会执行catch
            obj.name = 'zhangsan'
        }catch(err){
            // 如果try语句出错了,就会执行catch,catch里的参数接收的就是try里的错误对象
            // e是接收错误对象
            console.log(err)
        }
        console.log(123)
    </script>
</body>
</html>






Error

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var a = -20
        if (a > 0) {
            // 正常逻辑代码
            } else {
            // 本身代码不会报错,我们制造报错
             console.error(new Error('a不大于0,我给你报个错'))
            }
    </script>
</body>
</html>






Date

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var date = new Date() // 得到的是当前时间对象
        console.log(date)
        console.log(typeof date) // object

        console.log(Date.now()) // 获取的是当前的时间戳

        // 获取任意时间的时间对象
        // Date对象里的月份是 0~11,但是日期又是正常1开始
        var date1 = new Date(2008,2,1,8,2,3)
        console.log(date1)
    </script>
</body>
</html>





Date-API

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var date = new Date()
        console.log(date)

        console.log(date.getFullYear())
        console.log(date.getYear()) // 现在已经不用了,获取的是1900到当前年份的差值
        console.log(date.getMonth()) // 月份是 0~11
        console.log(date.getDate()) // 得到日期的号数

        console.log(date.getHours())
        console.log(date.getMinutes())
        console.log(date.getSeconds())

        console.log(date.getDay()) // 获取星期几 0~6,星期天就是0

        console.log(date.getMilliseconds()) // 获取当前日期的毫秒(一般用不到)1秒===1000毫秒

        console.log('------------')

        // 还有一系列设置API,可以把日期拨到某个时间点
        date.setFullYear(2021) // 把date日期对象设置为2021年

        date.setMonth(6) // 把日期拨到6月

        date.setDate(20) // 把日期设置成20号

        // date.setDay() // 设置时间戳,date就会根据时间戳来计算,设置为0那么date九变成了1970-1-1,这个方法一般用的不多
        console.log(date)
    </script>
</body>
</html>
发布了60 篇原创文章 · 获赞 3 · 访问量 538

猜你喜欢

转载自blog.csdn.net/dfc_dfc/article/details/105499436
今日推荐