黑马pink JavaScript学习笔记_JS基础 Day5

对象语法介绍

什么是对象?

对象是JavaScript的一种数据类型,它是由属性和方法两部分组成。

语法

声明对象

let person = {};
let person = {
"name": "summer",
"age": 18
};

对象基本使用

属性和访问

  • 属性都是成对出现的,属性名和属性值之间用冒号 : 分隔
  • 多个属性之间用逗号 , 分隔
  • 属性就是依附在对象上的变量
  • 属性名可以使用双引号 " " 或 单引号 ' ' 包着,一般情况下省略它们
  • 可以使用 对象名.属性名 或者 对象名['属性名'] 访问对象中的属性 (方括号里面的属性名一定要加引号)
let person = {
name: "dan",
age: 18,
hobby: "climbing, reading"
}

使用.访问属性:对象.属性名

let person = {
name: "dan",
age: 18,
hobby: "climbing, reading"
}
console.log("通过 . 访问对象属性");
console.log(person.name);
console.log(person.age);
console.log(person.hobby);
console.log("通过 [] 访问对象属性");
console.log(person[name]);//undefined
console.log(person[age]);//undefined
console.log(person[hobby]);//undefined

image-20240716225841828

使用[]访问属性:对象['属性名']

let person = {
name: "dan",
age: 18,
hobby: "climbing, reading"
}
console.log("通过 . 访问对象属性");
console.log(person.name);
console.log(person.age);
console.log(person.hobby);
console.log("通过 [] 访问对象属性");
// console.log(person[name]);//undefined
// console.log(person[age]);//undefined
// console.log(person[hobby]);//undefined
console.log(person["name"]);//undefined
console.log(person["age"]);//undefined
console.log(person["hobby"]);//undefined
console.log(person['name']);//undefined
console.log(person['age']);//undefined
console.log(person['hobby']);//undefined

image-20240716230130321

特殊情况:如果属性名是这种带中划线的命名方式,那么只能用[]这种形式来访问属性。

let phone = {
"good-name": "xiaomi"
}
console.log(phone['good-name']);

动态添加属性

let person = {
name: "dan",
age: 18,
hobby: "climbing, reading"
}
person.hometown = "重庆市";
console.log(person);

image-20240717071727212

方法和调用

一般对象外面的叫函数,对象里面的叫方法。方法的本质其实也是函数。

  1. 方法是由方法名和函数两部分构成,它们之间用 : 分隔
  2. 多个方法之间用 , 分隔
  3. 方法是依附在对象中的函数
  4. 和属性名一样,方法名也可以使用双引号 " " 或 单引号 ' ' 包着,一般情况下省略它们,除非遇到特殊符号,比如空格、中划线等。
let person = {
dance: function () {
console.log("ali真的很会跳舞~~~");
},
//方法之间用逗号分隔
sing: function () {
console.log("summer在唱课堂上老师教的新歌曲~~~");
}
}

使用.调用对象中的方法:对象名.方法名()

let person = {
dance: function () {
console.log("ali真的很会跳舞~~~");
},
//方法之间用逗号分隔
sing: function () {
console.log("summer在唱课堂上老师教的新歌曲~~~");
}
}
person.dance();//调用方法,这个小括号里面传递的参数为实参
person.sing();

image-20240715210757449

调用一个函数的时候,如果函数没有返回值,则默认会返回一个undefined

let person = {
dance: function () {
}
}
var result = person.dance();
console.log("result: " + result);

image-20240717072905489

null

null也是JavaScript中的一种数据类型,通常只用它来表示不存在的对象。

let person = null
console.log("typeof null: " + typeof person);

image-20240717073204450

使用for in遍历对象

通过for in 遍历对象,for in语法中的k是一个变量,在循环的过程中依次代表对象的属性名。因为k是变量,所以必须使用[ ]语法解析

image-20240715212706961

let person = {
name: "dan",
age: 18,
hobby: "climbing, reading"
}
for (const key in person) {
console.log(key);//key依次代表的值为 'name' 'age' 'hobby'
console.log(person.key);//所以不能通过这种方法访问
}

image-20240715213503854

let person = {
name: "dan",
age: 18,
hobby: "climbing, reading"
}
for (const key in person) {
console.log(key);
//console.log(typeof key);//String
//console.log(person.key);//获取到的对象属性的值为undefined
console.log(key + "->" + person[key]);
}

image-20240715213811547

案例:遍历数组对象

let students = [
{ name: "丹丹", age: 18, gender: '女', hometown: '陕西省' },
{ name: "阿力", age: 19, gender: '男', hometown: '重庆市' }
]
for (let i = 0; i < students.length; i++) {
let student = students[i];
console.log("第" + (i + 1) + "号猿神============>");
console.log("姓名:" + student.name + ", 年龄:" + student.age + ", 性别:" + student.gender + ", 籍贯:" + student.hometown);
}

image-20240716195938652

老师讲解之前自己写的代码

let students = [
{ name: "丹丹", age: 18, gender: '女', hometown: '陕西省' },
{ name: "阿力", age: 19, gender: '男', hometown: '重庆市' }
]
for (let i = 0; i < students.length; i++) {
let student = students[i];
console.log("第" + (i + 1) + "号猿神============>");
for (const key in student) {
console.log(key + "->" + student[key]);
}
}

image-20240723063520228

案例:渲染学生信息表

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
width: 600px;
text-align: center;
}
table,
th,
td {
border: 1px solid #ccc;
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: #ddd;
}
table tr:not(:first-child):hover {
background-color: #eee;
}
</style>
</head>
<body>
<h2>学生信息</h2>
<p>实现将数据渲染到页面中的功能...</p>
<table>
<caption>学生列表</caption>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>家乡</th>
</tr>
<script>
let students = [
{ name: "丹丹", age: 18, gender: '女', hometown: '陕西省' },
{ name: "阿力", age: 19, gender: '男', hometown: '重庆市' }
]
for (let i = 0; i < students.length; i++) {
let student = students[i];
//document.write中的write就是一个对象中的方法
document.write(`
<tr>
<td>${i + 1}</td>
<td>${student.name}</td>
<td>${student.age}</td>
<td>${student.gender}</td>
<td>${student.hometown}</td>
</tr>
`)
}
</script>
</table>
</body>
</html>

image-20240723063648763

内置对象

什么是内置对象?

内置对象是JavaScript内部提供的对象,包含各种属性和方法供开发者调用。

内置对象-Math

Math对象在线文档

Math对象有属性也有方法

image-20240717080218807

方法 描述
Math.abs() Math.abs(x) 函数返回一个数字的绝对值。
Math.ceil() Math.ceil() 静态方法总是向上舍入,并返回大于等于给定数字的最小整数。
Math.floor() Math.floor() 函数总是返回小于等于一个给定数字的最大整数。
Math.max() Math.max() 函数返回作为输入参数的最大数字,如果没有参数,则返回 -Infinity
Math.min() Math.min() 函数返回作为输入参数的数字中最小的一个,如果没有参数,则返回 Infinity
Math.pow() Math.pow() 函数返回基数(base)的指数(exponent)次幂,即 base^exponent
Math.random() Math.random() 静态方法返回一个大于等于 0 且小于 1 的伪随机浮点数,并在该范围内近似均匀分布,然后你可以缩放到所需的范围。其实现将选择随机数生成算法的初始种子;它不能由用户选择或重置。
Math.round() Math.round() 函数返回一个数字四舍五入后最接近的整数。

生成任意范围随机数

生成0-10的随机数呢?

Math.floor(Math.random() * (10 + 1))

生成5-10的随机数?

Math.floor(Math.random() * (5 + 1)) + 5

生成N-M之间的随机数(包含N和M)

Math.floor(Math.random() * (M - N + 1)) + N

随机点名案例

image-20240717195907665

let arr = ['赵云', '黄忠', '关羽', '张飞', '马超', '刘备', '曹操'];
let index = Math.floor(Math.random() * 7);
document.write(arr[index]);

随机点名案例改进

image-20240717195826579

//随机抽一个,并且抽完之后将其从数组中删掉
let arr = ['赵云', '黄忠', '关羽', '张飞', '马超', '刘备', '曹操'];
let index = Math.floor(Math.random() * 7);
console.log("随机抽出的元素是:" + arr[index]);
//splice(起始位置,要删除的元素个数)
arr.splice(index, 1);
console.log("移走元素后,数组所剩的元素有:" + arr);

image-20240717200720282

猜数字游戏

image-20240717200844136

//Math.floor(Math.random() * (M - N + 1)) + N
let random = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
console.log(random);
while (true) {
let userInput = +prompt("请输入你猜测的数字:");
if (userInput > random) {
alert("你猜大了,请继续猜哦");
} else if (userInput < random) {
alert("你猜小了,请继续猜哦");
} else if (userInput == random) {
alert("太棒啦,你猜对啦");
break;
}
}

image-20240717202641271

image-20240717202650061

image-20240717202735541

image-20240717202800486

猜数字游戏优化

设置最大猜测次数,最大只能猜测3次,如果3次都没有猜对,则弹出提示"次数已经用完啦,请下次再尝试哦~"。

//Math.floor(Math.random() * (M - N + 1)) + N
let random = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
console.log(random);
let flag = true;
for (let i = 0; i < 3; i++) {
let userInput = +prompt("请输入你猜测的数字:");
if (userInput > random) {
alert("你猜大啦");
} else if (userInput < random) {
alert("你猜小啦");
} else if (userInput == random) {
alert("太棒啦,你猜对啦");
flag = false;//如果猜对了,将标志设为false
break;
}
}
if (flag) {
alert("次数已经用完啦,请下次再尝试哦~");
}

生成随机颜色

image-20240717203924410

老师讲解之前,我自己试着写了一遍

//Math.floor(Math.random() * (M - N + 1)) + N
let random = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function getRandomColor(flag) {
if (flag = null || flag) {
//生成一个16进制的颜色
let result = "#";
for (let i = 1; i <= 6; i++) {
let random = Math.floor(Math.random() * (15 - 0 + 1)) + 0;
result += arr[random];
}
return result;
} else {
//生成rgb颜色
let result = "rgb(";
for (let i = 1; i <= 3; i++) {
let random = Math.floor(Math.random() * (255 - 0 + 1)) + 0;
if (i == 3) {
result += random;
} else {
result += random + ",";
}
}
result.substring(result.length - 3);
result += ")";
return result;
}
}
console.log(getRandomColor(true));
console.log(getRandomColor(false));

image-20240717210123043

看了老师讲解之后,按照老师的写法写的代码

//Math.floor(Math.random() * (M - N + 1)) + N
let random = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function getRandomColor(flag = true) {//如果不传参数,默认为true
if (flag) {
//生成一个16进制的颜色
let result = "#";
for (let i = 1; i <= 6; i++) {
let random = Math.floor(Math.random() * (15 - 0 + 1)) + 0;
result += arr[random];
}
return result;
} else {
//生成rgb颜色
let r = Math.floor(Math.random() * (255 - 0 + 1)) + 0;
let g = Math.floor(Math.random() * (255 - 0 + 1)) + 0;
let b = Math.floor(Math.random() * (255 - 0 + 1)) + 0;
return `rgb(${r},${g},${b})`;
}
}
console.log(getRandomColor(true));
console.log(getRandomColor(false));
console.log(getRandomColor());

image-20240717210627466

image-20240717210645937

posted @   growingbambi  阅读(56)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示