Javascript对象

一、Object对象

1.1 以字典的形式定义

 var obj = {
            "name":"张三",
            "age":10
        }
        
        // 添加/修改
        obj["sex"] = "男性"
        // 删除
        delete obj["sex"]
        // 获取
        console.log(obj["name"],typeof(obj))

1.2 以对象形式定义

 var obj2 = {
            name:"李四",
            age:80,
            eat:function(){
                console.log("喜欢吃黄豆,喝凉水")
            }
        }
        console.log(obj2,typeof(obj2))
        // 添加/修改
        obj2.age = 38
        obj2.skill1 = function(something){
            console.log(something)
        }
        // 获取
        console.log(obj2.age)
        obj2.skill1("打豆豆")
        // 删除
        delete obj.age
        console.log(obj.age)

        // 获取时的注意点
        var str = "name"
        console.log(obj2.name) // ok
        console.log(obj2.str)  // undefined
        console.log(obj2[str]) // ok obj2["name"]

1.3 、自定义构造函数

/* 类比python中定义类的写法 this 等价于 self */
        function Person(name,age,sex){
            this.name = name;
            this.age = age;
            this.sex = sex;
            this.info = function(){
                console.log(`姓名:${this.name},年龄:${this.age}`);                
            }
            // 除非返回其他对象,否则都默认返回this本对象
            return this //本对象
            // return 1000 无效的数字,默认返回的是本对象
            // return obj2 // 其他对象
        }
        // 实例化对象
        var obj1 = new Person("张银",20,"野兽")
        console.log(obj1.sex)
        // obj1.info()
        console.log(obj1.name)
        console.log(obj1 , typeof(obj1))
        console.log(obj1 instanceof Person)

1.4 遍历对象

obj用的是1.3的实例化对象

 // 1.方法一
        for(var i in obj1){
            // console.log(i , typeof(i)) name age sex info
            if(i == "info"){
                obj1[i]()
            }else{
                console.log(obj1[i])
            }        
        }

        console.log("<===============4==============>")
        // 2.方法 with 直接获取成员值
        with(obj1){
            console.log(name)
            console.log(age)
            console.log(sex)
            info()
        }

二、json对象

  var data = {
            'name':"耿择时",
            "age" : 88
        }

        // js对象 => json格式的字符串 [转化为json字符串时 , 强制转化成双引号]
        var res = JSON.stringify(data);
        console.log(res , typeof(res));

        res = '{"name":"王文","age":18}'  // success [反解json字符串时,字符串的键必须是双引号]
        res = "{'name':'王文','age':18}"  // error   字典的键不能是单引号
        
        // json格式的字符串 => js对象
        var data = JSON.parse(res)
        console.log(data,typeof(data)) 

三、字符串对象

        //1.获取字符串长度 length    
        var string = "good good study day day up"
        var res = string.length
        var res = string[-1] //不支持逆向下标 undefined
        console.log(res)

        //2.清除两侧的空白 trim [ python的strip ]
        var string = "   good good study day day up     "
        console.log(string.trim())

        //3.获取首次出现的位置 indexOf   [ python的 find ]
        // 如果找不到返回-1
        var string = "good good study day day up study study "
        var res = string.indexOf("study") // 10
        var res = string.indexOf("study",15,90) // 27
        var res = string.indexOf("study1111111") // -1
        console.log(res)

        //4.最后一次出现的位置 lastIndexOf 
        var res = string.lastIndexOf("study")     //33
        var res = string.lastIndexOf("study",3,6) //-1
        console.log(res) // 33

        //5.连接字符串    concat     [ python的 os.path.join  + ]
        var string = ""
        var res = string.concat("c:\","3000soft\","lianxi\")
        console.log(res)

        //6.大小写 toUpperCase toLowerCase [python的 upper lower]
        var string = "good good study day day up study study "
        var res = string.toUpperCase()
        console.log(res) // GOOD GOOD STUDY DAY DAY UP STUDY STUDY

        var res = res.toLowerCase()
        console.log(res)

        //7.截取字符串 slice
        // slice(开始值,结束值) 字符串切片 留头舍尾 从左到右 [支持逆向下标]
        var string = "good good study day day up study study"
        var res = string.slice(3,9)
        var res = string.slice(-5,-1)
        var res = string.slice(-5) // 从-5截取到最后
        console.log(res)

        //8.拆分字符串 split  [ python的split ]
        var string = "good good study day day up study"
        var res = string.split(" ")
        console.log(res)

        //9.search 匹配第一次找到的索引位置
        // 找不到数据直接返回-1
        var string = "the shy is a big father"
        var res = string.search(/b.*?g/)
        var res = string.search(/ccc/)
        console.log(res)

        //10.match 返回匹配的数据
        // /正则表达式/修饰符   i : 不区分大小写 m : 多行匹配  g:全局匹配
        var string = "the shy is a big father shy saby sccy"
        var string1 = string.match(/s.*?y/g)
        var string2 = string.match(/sS*?y/g)
        var string3 = string.match(/shy/g)
        console.log(string3)

        //11.字符串替换 replace
        // 方法一
        var string = "to be or not to be"
        var res = string.replace("to","three")
        console.log(res , typeof(res))

        // 方法二
        var res = string.replace(/to/g,"three")
        console.log(res , typeof(res))

        // 方法三
        console.log("<===============>")
        // string 原字符串 a 被替换的字符串 b 替换成什么
        function myreplace(string , a , b){
            /*
            一直做替换,直到 lastIndexOf 返回-1
            代表替换完毕
            */
            while(string.lastIndexOf(a) != -1){
                console.log("ok")
                string = string.replace(a,b)
            }
            return string
        }
        var res = myreplace(string,"to","four")
        console.log(res)

四 、数组对象

 // 定义数组
        var arr = []
        console.log(arr,typeof(arr))
        // 一.增
        arr[0] = 100
        arr[1] = 200
        arr[2] = 300
        arr[10] = 400
        console.log(arr,typeof(arr))

        // (1) push 从数组的最后插入元素 [python 的 append]
        var arr = []
        arr.push(100)
        arr.push(200)
       
        // (2) unshift 从数组的前面插入元素 [python 的 insert]
        arr.unshift(99)
        arr.unshift(98)
        console.log(arr,typeof(arr))

        // (3) concat 迭代追加数据 [python 的 extend]
        var arr = []
        var arr1 = [1,2,3]
        var arr2 = [7,8,9]
        // 迭代追加多个数据,如果是可迭代性数据会一个个把其中的内容追加进去,返回新数组
        var res = arr.concat(arr1,arr2)
        var res = arr.concat(1,2,3,4)
        console.log(res)
        // 二.删
        // (1) delete删除 原位置用空保留,获取值是undefined
        var arr = [100,200,300,400]
        delete arr[2]
        console.log(arr)
        
        // (2) pop 从后面删 , 返回删除的元素
        var arr = [100,200,300,400]
        var res = arr.pop()
        console.log(arr,res,"<=================>")

        // (3) shift 从前面删除
        var arr = [100,200,300,400]
        var res = arr.shift()
        console.log(arr,res)

        // (4) splice 从指定位置往后删除/添加
        // splice(开始位置,删除几个,[添加几个元素])
        var arr = [100,200,300,400,"尤佳","黄常见","朱培峰","李琦"]
        // 效果1 , 从4下标开始删,删2个
        var res = arr.splice(4,2)
        // 效果2 , 从4下标开始删,删2个,并且添加 王永娟,荷叶2个元素
        var res = arr.splice(4,2,"王永娟","荷叶")
        // 效果3 , 模拟 python insert 操作
        var res = arr.splice(4,0,"草配线")
        console.log(arr,res)

        // 三.改查
        var arr1 = [1,2,3]
        arr1[0] = 200
        console.log(arr1,arr1[0])

        // 四.数组的其他方法
        // join 拼接字符串 和split是一对
        var arr = ["no","can","no","bb"]
        var res = arr.join("-")
        console.log(res)

        // 数组反转 reverse
        var arr = [1,100,-3,4]
        var res = arr.reverse()
        console.log(res)
        console.log(arr)

        //截取数组的一部分 slice [python列表切片]
        // slice(开始值,结束值) 字符串切片 留头舍尾 从左到右 [支持逆向下标]
        var arr = ["梁新宇","孙杰龙","赵沈阳","李雅琪","王雨涵","石磊","吕菲菲"]
        var res = arr.slice(2,4)
        var res = arr.slice(-3,-1)
        var res = arr.slice(-2)
        console.log(res)

        // sort 排序
        // sort 会把数据当成字符串,按照ascii编码排序
        var arr = [1,3,13,15,2]
        var res = arr.sort()
        console.log(res , arr)

        // 当成正常的数据大小排序 //冒泡排序
        // 使用比值函数  应该返回一个负,零或正值
        // 正=>交换 负=>不交换
        var arr = [1,3,13,15,2,-100]

        // 1.普通函数
        function bizhi(a,b){
            if(a>b){
                return 1
            }else{
                return -1
            }
        }

        var res = arr.sort(bizhi)
        console.log(res)

        // 2.匿名函数 (推荐)
        var res = arr.sort(function(a,b){
            return a>b?1:-1
        })

        // 3.箭头函数
        console.log("<============>")
        var res = arr.sort((a,b) => {return a>b?1:-1})        
        console.log(res)

五、数学对象相关方法

 //四舍五入round
        var res = Math.round(3.5)
        console.log(res)
        var res = Math.round(4.51)
        console.log(res)

        //最大值 max
        var res = Math.max(1,2,3,4,100)
        console.log(res)
        //最小值 min
        var res = Math.min(1,2,3,4,100)
        console.log(res)
        //绝对值 abs
        var res = Math.abs(-100)
        console.log(res)


        //向下取整 floor 地板
        var res = Math.floor(1.19)
        console.log(res)
        //向上取整 ceil 天花板
        var res = Math.ceil(1.1)
        console.log(res)

        //幂运算 pow
        var res = Math.pow(2,3)
        console.log(res)

        //开方运算 sqrt
        var res = Math.sqrt(16)
        console.log(res)

        //获取从0到1随机值  0<x<1
        var res = Math.random()
        console.log(res)
        
        //获取从 m 到 n 的随机值   5,14之间的整数 实现python中randrange效果
        // 0<x<1 => 1<=x<=10
        var res = Math.ceil(   Math.random() * 10   ) 
        var res = Math.ceil(   Math.random() * 10   ) + 4
        /*
        // 推导过程
        // m = 5  n = 14
        var res = Math.ceil(   Math.random() * (14-5+1)   ) + (5-1)
        var res = Math.ceil(   Math.random() * (n-m+1)   ) + (m-1)
        */
        // 结论:封装函数
        function randrange(m,n){
            return Math.ceil(   Math.random() * (n-m+1)   ) + (m-1)
        }       

        var res = randrange(1000,1010)
        console.log(res)  

六、日期对象 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Date对象_查看时间效果</title>
    <style>
        #time
        {
            width:600px;
            height:50px;
            border:dotted 1px green;
            text-align: center;
            line-height: 50px;
            background:black;
            color:red;
            border-radius: 30px;
            font-weight: bold;
            font-size:20px;
        }
    </style>
</head>
<body>

    <div id="time"></div>

    <script>
        
        // 获取div这个标签的节点对象
        var obj2 = document.getElementById("time")
        console.log(obj2)
        function clock(){
            var obj = new Date()
            console.log(obj)
            //获取年  getFullYear
            var year = obj.getFullYear()
            console.log(year)
            //获取月份 getMonth 月份的索引是从 0 开始的
            var month = obj.getMonth()
            console.log(month) // 0 => 1月份
            //获取日期 getDate
            var date = obj.getDate()
            console.log(date)
            //获取小时 getHours
            var hour = obj.getHours()
            console.log(hour)
            //获取分钟 getMinutes
            var minutes = obj.getMinutes()
            console.log(minutes)
            //获取秒   getSeconds
            var seconds = obj.getSeconds()
            console.log(seconds)

            var abc = null;
            switch(month){
                case 0:
                    abc = "jan"
                    break;
                case 1:
                    abc = "Tu"
                    break;
                default:
                    abc = "没有"
                    break;
            }

            strvar = `现在的时间是:${year}年-${abc}月-${date}日 ${hour}:${minutes}:${seconds}`
            // 往div标签中插入内容  innerHTML
            obj2.innerHTML = strvar
            // console.log(strvar)
            // document.write(strvar)
        }

        var id = window.setInterval(clock,1000)

    </script>

    
</body>
</html>
原文地址:https://www.cnblogs.com/yj0405/p/14766442.html