前端学习4 | js对象

31 阅读1分钟

01. 什么是对象

  • 对象 (object):JavaScript里的一种数据类型
  • 可以理解为是一种无序的数据集合,注意数组是有序的数据集合
  • 通常用来描述某个事物,例如描述一个人

02. 对象使用

对象声明语法

let 对象名={}
let 对象名 = new Object()

对象的组成

属性+方法

let 对象名 = {
    属性名:属性值,
    方法名:函数
}

使用对象

查:对象.属性 对象['属性']
改:对象.属性 = 新值
增:对象.新属性 = 新值
删:delete 对象.属性

对象的方法

let obj{
uname:'刘德华'
song: function(){
    console.log('冰雨')
    }
}
obj.song()

03. 遍历对象

目标: 能够遍历输出对象里面的元素
遍历对象
for遍历对象的问题:

  • 对象没有像数组一样的length屈性,所以无法确定长度
  • 对象里面是无序的键值对,没有规律不像数组里面有规律的下标
属性名:
for(let k in obj){
    console.log(k)
}
属性值:
for(let k in obj){
    console.log(obj[k])
}

一个页面自动渲染的例子


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>页面渲染</title>
</head>
<style>
    table{
        width : 600px;
        text-align:center;
    }
    table,
    th,
    td{
        border: 1px solid #cccccc;
        border-collapse: collapse;
    }
    caption{
        font-size: 18px;
        margin-bottom: 10px;
        font-weight: 700;
    }
    tr{
        height: 40px;
        cursor: pointer;
    }
    table tr:nth-child(1){
        background-color: #cccccc;
    }
    table tr:not(:first-child):hover{
        background-color: #eae2b7;
    }

</style>
<body>
<table>
    <caption>学生表格</caption>
    <tr>
        <th>序号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
    </tr>
    <script>
        let students=[
            {name:'李健' , age:24 , gender:'男'},
            {name: '荣誉茉', age: 20, gender: '女'},
            {name: '李鹏', age: 27, gender: '男'},
            {name: '王莹', age: 20, gender: '女'}
        ]
        for(let i = 0;i<students.length;i++){
            document.write(`
            <tr>
                <td>${i+1}</td>
                <td>${students[i].name}</td>
                <td>${students[i].age}</td>
                <td>${students[i].gender}</td>
            </tr>

            `)
        }

    </script>
</table>
</body>
</html>

04. 内置对象

JavaScript内部提供的对象,包含各种属性和方法给开发者调用 document.write() console.log()
数学内置对象 Math.PI Math.Max() Math.random()
生成任意范围随机数
Math.random()随机数函数,返回一个0 - 1之间,并且包括0不包括1的随机小数[0,1)

  • 如何生成0-10的随机数呢?
    • Math.floor(Math.random()*(10+1))
  • 如何生成5-10的随机数?
    • Math.floor(Math.random()*(5+1))+5