目录
JS基础Day4
重点内容:函数
函数
1 匿名函数
匿名函数有两种写法:1函数表达式 2立即执行函数
1.1 函数表达式
写法:
let 函数名 = function(参数列表){函数内容};
使用方法与具名函数类似,但略有不同:
<!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>
// 匿名函数和具名函数的不同
//1 匿名函数可以直接打印出来,而具名函数不能
let fun = function () {alert("我是匿名函数")};
alert(fun);
//2 匿名函数只有在声明后才能使用
fun2();
function fun2 () {alert("我是具名函数")} // 正常调用
fun3();
let fun3 = function () {alert("我是匿名函数")}; // 报错
</script>
</body>
</html>
效果演示:
1.2 立即执行函数
写法:
(function (形参列表) {函数内容}) (实参列表); // 写法1
(function (形参列表) {函数内容} (实参列表)); // 写法2
立即执行函数会自动调用,防止变量污染,而不能手动调用。
综合案例
需求:用户输入秒数,可以自动转换为时分秒
<!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>
let second = +prompt("请输入秒数:");
function getTime (t) {
let h = parseInt(t / 60 / 60 % 24);
let m = parseInt(t / 60 % 60);
let s = parseInt(t % 60);
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
s = s < 10 ? '0' + s : s;
return `转换结果:${h}小时${m}分${s}秒`;
}
alert(getTime(second));
</script>
</body>
</html>
JS基础Day5
重点内容:对象
对象
1 对象的属性
两种访问对象属性的方法:
对象.属性 // 方法一
对象['属性'] // 方法二 可以使用字符串作为属性名,摆脱了变量命名的限制
2 遍历对象
写法:
// 声明对象
let obj = {
属性名1:属性1,
属性名2:属性2,
......
}
// 取值
for (let key in obj) {
alert(obj[key]); // alert属性值
}
利用for in遍历对象,要注意for in取出来的值是字符串类型的属性名。
练习
需求:
请把下面数据中的对象打印出来:
// 定义一个存储了若干学生信息的数组
let students = [
{ name: '小明', age: 18, gender: '男', hometown: '河北省' },
{ name: '小红', age: 19, gender: '女', hometown: '河南省' },
{ name: '小刚', age: 17, gender: '男', hometown: '山西省' },
{ name: '小丽', age: 18, gender: '女', hometown: '山东省' },
{ name: '晓强', age: 16, gender: '女', hometown: '蓝翔技校' }
]
<!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写到这里 -->
<script>
// 1. 数据准备
let students = [
{ name: '小明', age: 18, gender: '男', hometown: '河北省' },
{ name: '小红', age: 19, gender: '女', hometown: '河南省' },
{ name: '小刚', age: 17, gender: '男', hometown: '山西省' },
{ name: '小丽', age: 18, gender: '女', hometown: '山东省' },
{ name: '晓强', age: 16, gender: '女', hometown: '蓝翔技校' }
]
// 2. 渲染页面
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>
<td>${students[i].hometown}</td>
</tr>
`)
}
</script>
</table>
</body>
</html>
3 数学内置对象(Math)
3.1 属性
Math.PI:圆周率
3.2 方法
random:生成0-1之间的随机数(包含0不包括1,也即[0,1))
ceil:向上取整
floor:向下取整
round:四舍五入(实则是就近原则,遇0.5则向上取整)
max:找最大数
min:找最小数
pow:幂运算
abs:绝对值
随机数练习1
// 生成0到10的随机整数
alert(Math.floor(Math.random() * (10 + 1)));
// 生成5到10的随机整数
alert(Math.floor(Math.random() * (5 + 1)) + 5);
// 生成N到M的随机整数
alert(Math.floor(Math.random() * (M - N + 1)) + N);
需求:请把['赵云','黄忠','关羽','张飞','马超','刘备','曹操']随机显示一个名字到页面中
function getRandom(N, M) {
return Math.floor(Math.random() * (M - N + 1)) + N;
}
let names = ['赵云', '黄忠', '关羽', '张飞', '马超', '刘备', '曹操'];
let random = getRandom(0, names.length - 1);
document.write(names[random]);
改进版需求:请把['赵云','黄忠','关羽','张飞','马超','刘备','曹操']随机显示一个名字到页面中,但是不允许重复显示
function getRandom(N, M) {
return Math.floor(Math.random() * (M - N + 1)) + N;
}
let names = ['赵云', '黄忠', '关羽', '张飞', '马超', '刘备', '曹操'];
let length = names.length;
for (let i = 0; i < length; i++) {
let random = getRandom(0, names.length - 1);
document.write(names[random]);
names.splice(random, 1);
}
随机数练习2
需求:程序随机生成1~10之间的一个数字,用户输入一个数字
①如果大于该数字,就提示,数字猜大了,继续猜
②如果小于该数字,就提示,数字猜小了,继续猜
③如果猜对了,就提示猜对了,程序结束
function getRandom(N, M) {
return Math.floor(Math.random() * (M - N + 1)) + N;
}
num = getRandom(1, 10);
while (true) {
input = +prompt("输入一个1~10之间的数字:");
if (input == num) {
alert("猜对了!");
break;
} else if (input > num) {
alert("数字猜大了,继续猜");
} else {
alert("数字猜小了,继续猜");
}
}
随机数练习3
需求:该函数接收一个布尔类型参数,表示颜色的格式是十六进制还是rgb格式。
①如果参数传递的是true或者无参数,则输出一个随机十六进制的颜色
②如果参数传递的是false,则输出一个随机rgb的颜色
③格式:
function getRandomColor(flag) { }
console.log(getRandomColor(true)) // #ffffff
console.log(getRandomColor(false)) // rgb(255,255,255)
分析:
提示:16进制颜色格式为:‘#ffffff',其中f可以是任意0-f之间的字符。
提示:rgb颜色格式为:'rgb(255,255,255)',其中255可以是任意0-255之间的数字。
function getRandomColor(flag = true) {
if (flag) {
let str = '#';
let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
for (let i = 0; i < 6; i++) {
let random = Math.floor(Math.random() * arr.length);
str += arr[random];
}
return str;
} else {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return `rgb(${r},${g},${b})`
}
}
console.log(getRandomColor(true));
console.log(getRandomColor(false));
console.log(getRandomColor());
const div = document.querySelector('div');
div.style.backgroundColor = getRandomColor();
综合案例
需求:根据数据渲染列表页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>学车在线首页</title>
<link rel="stylesheet" href="./css/style.css">
<style>
</style>
</head>
<body>
<!-- 4. box核心内容区域开始 -->
<div class="box w">
<div class="box-hd">
<h3>精品推荐</h3>
<a href="#">查看全部</a>
</div>
<div class="box-bd">
<ul class="clearfix">
<!-- <li>
<a href="#">
<img src="images/course01.png" alt="">
<h4>
Think PHP 5.0 博客系统实战项目演练
</h4>
<div class="info">
<span>高级</span> • <span>1125</span>人在学习
</div>
</a>
</li> -->
<script>
let data = [
{
src: 'images/course01.png',
title: 'Think PHP 5.0 博客系统实战项目演练',
num: 1125
},
{
src: 'images/course02.png',
title: 'Android 网络动态图片加载实战',
num: 357
},
{
src: 'images/course03.png',
title: 'Angular2大前端商城实战项目演练',
num: 22250
},
{
src: 'images/course04.png',
title: 'AndroidAPP实战项目演练',
num: 389
},
{
src: 'images/course05.png',
title: 'UGUI源码深度分析案例',
num: 124
},
{
src: 'images/course06.png',
title: 'Kami2首页界面切换效果实战演练',
num: 432
},
{
src: 'images/course07.png',
title: 'UNITY 从入门到精通实战案例',
num: 888
},
{
src: 'images/course08.png',
title: 'Cocos 深度学习你不会错过的实战',
num: 590
},
{
src: 'images/course04.png',
title: '自动添加的模块',
num: 1000
}
]
//重点javascript代码
for (let i = 0; i < data.length; i++) {
document.write(`
<li>
<a href="#">
<img src=${data[i].src} title="${data[i].title}">
<h4>
${data[i].title}
</h4>
<div class="info">
<span>高级</span> • <span>${data[i].num}</span>人在学习
</div>
</a>
</li>
`)
}
</script>
</ul>
</div>
</div>
</body>
</html>
效果展示:
拓展
1 javascript引用数据类型
基本数据类型:在存储时变量中存储的是值本身(eg.string、number、boolean、undefined、null)
引用数据类型:在存储时变量中存储的仅仅是地址(引用),用new关键字创造的对象(eg.Object、Array、Date)
2 javascript堆栈空间分配区别
1、栈(操作系统):由操作系统自动分配释放存放函数的参数值、局部变量的值等。其操作方式类似于数据结构中的栈;简单数据类型存放到栈里面。
2、堆(操作系统):存储复杂类型(对象),一般由程序员分配释放,若程序员不释放,由垃圾回收机制回收。引用数据类型存放到堆里面。