一、对象
- 对象语法
let 对象名 = {
属性名:属性值,
方法:函数
}
-
对象有属性和方法组成
属性:信息或叫特征(名词);方法:功能或叫行为(动词)。
3.对象访问属性有两种方式:
➢ 点形式 对象.属性
➢ [] 形式 对象[‘属性’]
二、遍历对象
let person = {
name: '小小',
age: 18,
sex: '男'
}
利用 for in 遍历对象 key 代表属性名
for (let key in person) {
console.log(key);
在遍历对象的时候不能用 对象名.key的这种方式获取对象中的属性值
console.log(person.key);
当前遍历的属性值
console.log(person[key]);
} 三、学生信息表案例
// 定义一个存储了若干学生信息的数组
let students = [
{ name: '小白', age: 18, gender: '男', hometown: '广东省' },
{ name: '小花', age: 19, gender: '女', hometown: '四川省' },
{ name: '小黑', age: 17, gender: '男', hometown: '广西省' }
]
// 通过js的方式创建表格
// 1. 通过JS先把表头不动的部分先渲染加载出来
document.write(`
<table>
<caption>
<h3>学生列表</h3>
</caption>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>家乡</th>
</tr>
`)
// 2. 根据后台传回的数据 进行遍历动态的追加到页面中
// 遍历数组需要使用for循环 fa
for (let i = 0; i < students.length; i++) {
// students[i] 数组当中的每一项
// console.log(i, students[i])
// 想访问 数组中每一项的姓名
// console.log(students[i].name)
document.write(`
<tr>
<td>${i + 1}</td>
<td>${students[i].name}</td>
<td>${students[i].age}</td>
<td>${students[i].gender}</td>
<td>${students[i].hometown}</td>
</tr>
`)
}
// 3. 把table的结束标签也要渲染在页面上
document.write(` </table>`)
</script>
四、数学内置对象
Math.random() 求从0 - 1 的随机数(包括0 不包括1)
Math.ceil() 向上取整
Math.floor() 向下取整
Math.max() 求最大值
Math.min() 求最小值
四舍五入 Math.round()
五、随机数对象
// min - max 的随机数
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
console.log(getRandom(20, 40))
六、随机点名-不允许出现重复的
// 随机数
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
// 声明一个数组
let arr = ['赵云', '黄忠', '关羽', '张飞', '马超', '刘备', '曹操']
// 生成1个随机数 作为数组的索引号
let random = getRandom(0, arr.length - 1)
// console.log(random)
document.write(arr[random])
// 之后删除这个 人的名字
// arr.splice(从哪里开始删, 删几个)
arr.splice(random, 1)
console.log(arr);