六、ES2015基础语法
1.变量
用let代替var声明变量,用let声明的变量有块级作用域,即在语句块里声明的变量,在语句外无法访问,不存在变量提升,不允许重复声明
2.常量
用const定义常量,定义之后不可以修改,不变的值用常量声明,函数表达式和对象的声明(对象的属性可以改变)可以使用常量,引入外部模块也可以使用常量
function getObject(){
return {name:"haha"}
}
const cs=getObject();
cs.name="xiaoming"
console.log(cs.name)
3.模版字符串(`)
支持换行,支持嵌入变量
let year=`2023`;
let month=`10`;
let date=`2`;
let result=`${year}年${month}月${date}日`;
console.log(result)
4.解构赋值
(1)数组的解构赋值
给多个变量一次性赋值
eg1.
let [a,b,c]=[2,48,90]
一次给a,b,c分别赋值2,48,90
eg2.交换变量的值
let [a,b]=[35,48];
[a,b]=[b,a]
(2)对象的解构赋值
let {age,name}={name:"xiaoming",age:17}
console.log(name)
注:let后的对象中属性顺序改变,属性值也没变
(3)通过解构赋值传递参数
获取对象的属性
原来的做法:
let stu={name:"xiaoming",age:17}
function getName(obj){
return obj.name;
}
console.log(getName(stu))
现在改善:
let stu={name:"xiaoming",age:17}
function getName({name}){
return name;
}
console.log(getName(stu))
七、函数进阶
1.函数声明提升
即使是在调用之后声明函数,也可以调用成功
2.匿名函数
没有起名的函数
3.回调函数
将匿名函数作为参数传递给另外一个参数或方法
setInterval(function(){
console.log("hello")
},1000)
3.函数表达式
将函数赋给常量,可以被多次调用,与直接声明函数差不多,但没有函数提升的性质,即不可以在调用之后声明
const fun=function(n,m){
return n+m
}
console.log(fun(10,20))
4.方法
const cat={
name:"mao",
sayName(){
console.log(this.name)
}
}
cat.sayName();
5.设置默认参数值
函数传递了实参,则使用实参,没有传递,则使用设置的默认值
function fun(n=100,m=200){
return n+m;
}
let result=fun();
console.log(result)
该例未传递参数,则按默认值计算
let result=fun(2,4);
该例使用传入的实参计算
6.立即执行函数
声明之后直接调用,不可多次调用,某些第三方库直接实现封装,函数外的语句不可调用函数内的语句或变量
(function(){
函数体
})()
(function(){
let a=10;
let b=20;
console.log(a+b)
})()
7.作用域链
函数外部无法访问函数内部,但函数内部可以访问函数外部,当函数内部调用变量时,会先从函数内部找,即按照从内到外的顺序找,直到找到为止
8.闭包
(1)闭包函数:声明在一个函数中的函数
(2)闭包:内部函数总是可以访问其所在的外部函数中声明的参数和变量,即使在其外部函数被返回之后(内部函数被返回,外部函数不会被销毁)
function fun1(){
let n=10;
let m=20;
function fun2(){
return n+m;
}
return fun2()
}
const f=fun1();
console.log(f)
9.箭头函数
(1)格式:
const 函数名=参数 =>返回值;
const fun=function(x,y){
return x+y;
}
console.log(fun(2,4))
可以简化为:
const fun=(x,y)=>{
return x+y;
}
console.log(fun(2,4))
可以再化简为:
const fun=(x,y)=> x+y;
console.log(fun(2,4))
(2)this
箭头函数和普通函数的this指向不同,
使用function定义的函数,this取决于调用的函数
使用箭头函数,this取决于函数定义的位置
也就是说,
普通函数指向的是调用该函数的对象
箭头函数:在哪里定义,this就指向谁
const cat={
name:"mao",
sayName(){
setInterval(() =>{
console.log(this.name)
},1000)
}
}
cat.sayName()
八、面向对象
1.构造函数
构造函数的函数名首字母大写,是用来创建对象用的
function Dog(name,age){
this.name=name;
this.age=age;
}
var dog=new Dog("旺财",2);//创建对象
console.log(dog)
2.原型对象(prototype)
是构造函数的属性,可以通过原型对象,为构造函数生成的对象赋予新的方法,该构造函数的所有对象都可以调用
eg1.
function Dog(n,a){
this.name=n;
this.age=a;
}
Dog.prototype.sayName=function(){
console.log(`我的名字是${this.name}`)
}
var dog=new Dog("旺财",2);//创建对象
var newDog=new Dog("二哈",2);//创建对象
dog.sayName();//调用方法
newDog.sayName();
eg2.为数组增加新的方法
var arr=[1,2,3,4];
Array.prototype.sayHello=function(){
console.log(`我是一个数组,我的长度为${this.length}`)
}
arr.sayHello();
因为创建数组的语法为:var arr=new Array(1,2,3,4);
而上例为简写,故可以为数组增加新的方法
3.原型链
实现继承
function Animal(name){
this.name=name;
}
Animal.prototype.sayName=function(){
console.log(`你好,我是${this.name}`)
}
Animal.prototype.sayHello=function(){
console.log("Hello!!")
}
function Dog(name){
this.name=name;
}
Dog.prototype=new Animal();
var dog=new Dog("旺财");
dog.sayName();
dog.sayHello();
4.ES2015面向对象语法
(1)Class关键字
可以直接在类里创建构造函数与方法,并给对象调用
class Dog{
constructor(name,age){
this.name=name;
this.age=age;
}
sayName(){
console.log(`我是${this.name}`)
}
}
let dog=new Dog("旺财",2);
dog.sayName();
(2)继承
使用extends关键字表示继承
super表示父级的属性
class Animal{
constructor(name){
this.name=name;
}
sayName(){
console.log(`我是${this.name}`)
}
}
class Dog extends Animal{
}
}
let dog=new Dog("旺财");
dog.sayName();
也可以在子类中定义构造方法,传递参数
class Animal{
constructor(name){
this.name=name;
}
sayName(){
console.log(`我是${this.name}`)
}
}
class Dog extends Animal{
constructor(name,age){
super(name);
this.age=age;
}
}
let dog=new Dog("旺财");
dog.sayName();
eg3.扩展Date对象实现如下功能:实现dateFormate方法,返回值是“xxxx年xx月xx日”
Date.prototype.dateFormate=function(){
let year=this.getFullYear();
let month=this.getMonth();
let date=this.getDate();
return `${year}年${month+1}月${date}日`;
}
let d=new Date("2002-12-22");
let result=d.dateFormate();
console.log(result)
九、DOM
文档对象模型(document对象),是一套标准的编程接口,通过它来操作html元素
1.document对象
DOM通过documnt对象,为开发者提供了大量的接口(api)来操作DOM树
document.getElementById():通过id获取元素,返回值是一个dom节点
document.getElementsByClassName();:通过class名获取多个元素,返回值是一个dom节点的集合,若要获取非dom节点,应该遍历
document.querySelector();获取一个节点,若有多个class,返回第一个节点
document.querySelectorAll();通过选择器获取多个节点
element.innerHTML:获取和设置元素内的所有内容
eg1.修改h1内容
<h1 id="title">hello</h1>
<script>
h1.innerHTML="hello world";
</script>
</body>
这样h1的内容就被修改成了hello world
eg2.控制台输出h1内容
<h1 id="title">hello</h1>
<script>
let h1=document.getElementById("title");
console.log(h1);//控制台输出的是dom节点的集合
console.log(h1.innerHTML);//控制台输出的是h1内容
</script>
eg3.将所有按钮的内容改为test,因为btns为节点的集合,所以要遍历
<body>
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
<script>
let btns=document.getElementsByClassName("btn");
for(let i in btns){
btns[i].innerHTML="test"
}
</script>
eg4.通过选择器获取节点
let h1=document.querySelector("#title");
h1.innerHTML="hello world";
eg5.将所有按钮的内容改为test
let btns=document.querySelectorAll(".btn");
for(let i in btns){
btns[i].innerHTML="test";
2.事件类型
click:点击事件,要绑定事件,要在前面加一个on
mouseenter:鼠标移入元素
mouseleave:鼠标移出元素
eg1.点击按钮后,控制台出现hello btn
<button>按钮</button>
<script>
let btn=document.querySelector("button");
//事件监听函数:当事件被触发式时,函数会执行
btn.οnclick=function(){
console.log("hello btn")
}
</script>
eg2.当鼠标移入div时,控制台出现hello red字样,移出时,在控制台显示bye red
<style>
.box{
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<button>按钮</button>
<script>
let box=document.querySelector(".box");
box.οnmοuseenter=function(){
console.log("hello red")
}
box.οnmοuseleave=function(){
console.log("bye red")
}
</script>
</body>
3.设置样式
element.style.color
element.style.backgroundColor
通过click、mouseenter、mouseleave事件控制样式
eg1.鼠标移入div,则div变成蓝色,移出就变回红色
<style>
.box{
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<button>按钮</button>
<script>
let box=document.querySelector(".box");
box.οnmοuseenter=function(){
this.style.backgroundColor="blue";
}
box.οnmοuseleave=function(){
this.style.backgroundColor="red";
}
</script>
</body>
eg2.在上述例子的基础上,点击按钮,div变成黄色
<head>
<style>
.box{
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<button>按钮</button>
<script>
let btn=document.querySelector("button");
let box=document.querySelector(".box");
box.οnmοuseenter=function(){
this.style.backgroundColor="blue";
}
box.οnmοuseleave=function(){
this.style.backgroundColor="red";
}
btn.οnclick=function(){
box.style.backgroundColor="yellow";
}
4.设置属性
element.src
element.id:获取元素id
eg.点击不同按钮切换图片
<style>
img{
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div>
<img src="img1.png" alt="">
</div>
<button>1</button>
<button>2</button>
<button>3</button>
<script>
let img=document.querySelector("img");
let imagesSrcList = ["img1.png","img2.png","img2.png"];
let btns=document.querySelectorAll("button");
for(let i in btns){
btns[i].οnclick=function(){
img.src=imagesSrcList[i]
}
}
</script>
5.通过class属性设置样式
element.className
点击原始、设置激活的背景色
eg1.点击元素,则背景变成红色,再次点击,变回原来的颜色
<style>
.active{
background-color:red;
}
</style>
</head>
<body>
<h1>hello!!!!</h1>
<h1>hello!!!!</h1>
<h1>hello!!!!</h1>
<h1>hello!!!!</h1>
<h1>hello!!!!</h1>
<h1>hello!!!!</h1>
<script>
let h1List=document.querySelectorAll("h1");
for(let i in h1List){
h1List[i].οnclick=function(){
if(this.className==="active"){
this.className="";
}else{
this.className="active";
}
}
}
</script>
</body>
6.DOM节点操作
(1)节点分类
1)元素节点
获取元素节点:querySelector;querySelectorAll
2)文本节点
innerHTML:可以设置标签内部的内容
eg.点击按钮后,在ul中添加标签
<button>按钮</button>
<ul></ul>
<script>
let btn=document.querySelector('button');
let ul=document.querySelector('ul');
btn.οnclick=function(){
ul.innerHTML=`
<li>香蕉</li>
<li>苹果</li>
<li>鸭梨</li>
}
</script>
3)属性节点
element.src,element.id
(2)节点操作
创建元素节点:createElement
创建文本节点:createTextNode
添加节点:appendChild
删除节点:removeChild
eg1.点击按钮,添加一个节点
<button>按钮</button>
<ul></ul>
<script>
let btn=document.querySelector('button');
let ul=document.querySelector('ul');
btn.οnclick=function(){
let li=document.createElement('li');
let txt=document.createTextNode("香蕉")
ul.appendChild(li);
li.appendChild(txt);
}
</script>
eg2.点击按钮,输出列表的内容为用户输入的内容
<input type="text">
<button>按钮</button>
<ul></ul>
<script>
let btn=document.querySelector('button');
let ul=document.querySelector('ul');
let inp=document.querySelector('input');
btn.οnclick=function(){
let li=document.createElement('li');
let txt=document.createTextNode(inp.value)
//console.log(inp.value);//inp.value为按钮输入的内容
ul.appendChild(li);
li.appendChild(txt);
}
</script>
eg3.点击列表元素,则删除该元素
<ul class="fruit-list">
<li>香蕉</li>
<li>苹果</li>
<li>柿子</li>
</ul>
<script>
let list=document.querySelectorAll('.fruit-list li')
for(let i in list){
list[i].οnclick=function(){
ul.removeChild(this);}
}
</script>
十、事件
1.事件对象
事件监听函数的形参可以获取事件对象
通过事件对象可以获取鼠标点击的位置的坐标
(1)获取x坐标:e.clientX
(2)获取y坐标:e.clientY
eg1.获取鼠标点击位置的x坐标和y坐标
<style>
.box{
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
let box=document.querySelector(".box");
box.οnclick=function(event){
console.log(event.clientX);
console.log(event.clientY)
}
</script>
</body>
eg2.鼠标移入图片,显示放大的图片
<style>
.picture-list img{
width: 320px;
height: 160px;
}
.big-picture img{
width: 640px;
height: 320px;
}
.big-picture{
position: absolute;
}
</style>
</head>
<body>
<div class="picture-list">
<img src="img1.png" alt="">
<img src="img2.png" alt="">
<img src="img3.png" alt="">
</div>
<div class="big-picture"></div>
<script>
let imgList=document.querySelectorAll(".picture-list img");
let bigPicture=document.querySelector(".big-picture");
let pictureList=document.querySelector('.picture-list');
for(let i in imgList){
imgList[i].οnmοuseenter=function(){
bigPicture.innerHTML=`<img src='${this.src}'>`
}
imgList[i].οnmοuseleave=function(){
bigPicture.innerHTML=''
}
}
pictureList.οnmοusemοve=function(e){
let x=e.clientX;
let y=e.clientY;
bigPicture.style.top=y+10+"px";
bigPicture.style.left=x+10+"px";
}
</script>
2.绑定事件
(1)addEventListener(“eventType”,fun)
(2)element.onEventType=function(){}
如element.οnclick=function(){}
区别:
addEventListener在同一元素上的同一事件类型添加多个事件,不会被覆盖,而onEventType会覆盖
addEventListener可以设置元素在捕获阶段触发事件,而onEventType不能
eg1.点击按钮,在控制台输出hello
<button>按钮</button>
<script>
let btn=document.querySelector("button");
btn=addEventListener("click",function(){
console.log("hello")
})
</script>
3.事件流
(1)事件执行顺序
从外层到内层的事件流向叫事件捕获
从内层到外层的事件流向叫事件冒泡
默认情况下,事件会在冒泡阶段执行,addEventListener(eventTypr,fun,boolean),默认false为冒泡阶段执行,true为捕获阶段触发
三个div嵌套,都绑定click事件,点击最内层的元素,事件执行顺序为从内到外执行,若将addEventListener的boolean值改为true,点击最内层div,执行顺序为从外到内
<style>
.big{
width: 300px;
height: 300px;
background-color: red;
}
.medium{
width: 200px;
height:200px;
background-color: yellow;
}
.small{
width:100px;
height:100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="big">
<div class="medium">
<div class="small"></div>
</div>
</div>
<script>
let big=document.querySelector(".big");
let medium=document.querySelector(".medium");
let small=document.querySelector(".small");
big.addEventListener("click",function(){
console.log("Hi,I'm big!");
},true)
medium.addEventListener("click",function(){
console.log("Hi,I'm medium!");
},true)
small.addEventListener("click",function(){
console.log("Hi,I'm small!");
},true)
</script>
(2)阻止事件冒泡
e.stopPropagation()(e为function()的形参)
在对应的事件的函数语句里加上形参和这一语句,就不会执行其外面事件
如在small里加上,点击small后,不会触发其外层事件,但点击medium,会触发事件冒泡,即触发medium和big
但是,在此基础上,再在medium的函数里加上形参以及该语句,点击任一事件都不会触发事件冒泡
eg2.实现下面功能:
点击一个按钮,显示一个盒子容器
点击容器,容器背景颜色改变
点击容器中的按钮,容器隐藏
<style>
.box{
width: 200px;
height: 200px;
background-color: yellowgreen;
display: none;
}
</style>
</head>
<body>
<button class="show">显示</button>
<div class="box">
<button class="close">关闭</button>
</div>
<script>
let show=document.querySelector(".show");
let box=document.querySelector(".box");
let close=document.querySelector(".close");
show.οnclick=function(){
box.style.display="block";
}
close.οnclick=function(e){
box.style.display="none";
e.stopPropagation();
}
box.οnclick=function(){
this.style.backgroundColor="red";
}
</script>
(3)事件默认行为
去掉默认行为:
e.preventDefault();
或
return false;
eg3.为一个可以跳转到百度的a标签设置点击事件,即点击链接不发生跳转,而是在控制台输出hello
<a href="http://baidu.com">baidu</a>
<script>
let a=document.querySelector("a");
a.οnclick=function(e){
console.log("hello");
return false;
}
</script>
(4)事件委托
通过e.target将子元素的事件委托给父级处理
点击的为子级,但事件绑定给父级,将子级的事件委托给父级
eg.将输入的加入列表,同时,点击列表选项即可删除该选项
<input type="text">
<button>添加</button>
<ul class="fruit-list">
<li>香蕉</li>
<li>苹果</li>
<li>柿子</li>
</ul>
<script>
let btn=document.querySelector('button');
let inp=document.querySelector('input');
let ul=document.querySelector('.fruit-list')
btn.οnclick=function(){
let li=document.createElement('li');
let txt=document.createTextNode(inp.value)
li.appendChild(txt);
ul.appendChild(li);
ul.οnclick=function(e){
ul.removeChild(e.target);
}
}
</script>
(5)事件类型
1)鼠标事件
.onclick 鼠标点击触发事件
2)键盘事件
.onkeydown 键盘按下触发事件
<script>
document.οnkeydοwn=function(e){
console.log(e.keyCode)
}
</script>
点击键盘上不同按键会输出不同的码值
offsetLeft:元素左边偏移量
offsetTop:元素上方偏移量
3)触屏事件
.ontouchstart:鼠标按下
.ontouchend:鼠标松开
.ontouchmove:鼠标长按拖动
十一、计时器
1.setlnterval和clearInterval
(1)setInterval
setInterva(function(){},ms)
每次间隔多少毫秒执行一次函数(循环执行)
(2)clearInterval
可以停止setInterval的计时
eg1.点击按钮则停止输出
<button>暂停</button>
<script>
let btn=document.querySelector("button");
let timer=setInterval(()=>{
console.log("hello")
},1000)
btn.οnclick=function(){
clearInterval(timer);
}
</script>
eg2.在网页中制作一个秒表,有开始功能,停止功能,重置
<button class="start">开始</button>
<button class="pause">暂停</button>
<button class="stop">结束</button>
<h1 class="time">10:9</h1>
<script>
let start=document.querySelector(".start");
let pause=document.querySelector(".pause");
let stop=document.querySelector(".stop");
let time=document.querySelector(".time");
let seconds=0;
let ms=0;
time.innerHTML=`${seconds}:${ms}`;
let timer=null;
start.οnclick=function(){
clearInterval(timer);
timer=setInterval(()=>{
if(ms===9){
++seconds;
ms=0;
}
++ms;
time.innerHTML=`${seconds}:${ms}`;
},100)
}
pause.οnclick=function(){
clearInterval(timer);
}
stop.οnclick=function(){
seconds=0;
ms=0;
time.innerHTML=`${seconds}:${ms}`;
}
</script>
2.setTimeout和clearTimeout
(1)setTimeout
过多少毫秒执行函数(仅一次)
(2)clearTimeout
停止计时器
eg1.
<button>停止</button>
<script>
let timer=null;
document.querySelector("button").οnclick=function(){
clearTimeout(timer);
}
timer= setTimeout(()=>{
console.log("hello")
},1000)
原本会在1s后输出hello,若在此之前点击按钮,则不会输出
eg23s后跳转到百度
<script>
setTimeout(()=>{
location.href="http://baidu.com";
},3000)
</script>
3.防抖与节流
(1)防抖:对于短时间内多次触发事件的情况,可以使用防抖停止事件持续触发
window.onscroll:鼠标滚动事件(滚动鼠标或者拉滚动条都会触发)
eg1.只要鼠标滚动就会触发事件,性能不好
<script>
window.οnscrοll=function(){
console.log("hello")
}
</script>
eg2.改善:利用防抖,滚动停止才触发事件
<script>
let timer=null;
window.οnscrοll=function(){
if(timer!==null){
clearTimeout(timer);
}
timer=setTimeout(()=>{
console.log("hello");
timer=null;
},500)
}
</script>
开始滚动鼠标,初始时timer=null,先触发timer,即将在0.5秒后,执行setTimeout中的语句,但在这0.5秒内,再次滚动鼠标,此时timer已经不等于null,故触发if条件语句里的clearTimeout导致计时停止,进一步导致无法输出,在不断滚动的过程中,后一次滚动总是触发clearTimeout,导致前一次的滚动触发的timer计时停止,在不断滚动鼠标的过程不断触发timer和clearTimeout,开始计时又将计时停止,而当滚动鼠标停止,即在最后一次滚动时,只触发timer,先输出hello,再将计时器停止,故展现的效果为:滚动停止时,才输出
(2)节流:防止短时间内多次触发事件的情况,但是间隔时间内还是需要不断触发
eg3.鼠标滚动,每隔0.5s才输出一次
<script>
let mark=true;//标记,控制if语句是否执行
window.οnscrοll=function(){
if(mark){
setTimeout(()=>{
console.log("hello");
mark=true;
},500)
}
mark=false;
}
</script>
eg4.设置返回到页面顶部,同时,在顶部时,返回顶部按钮不显示,
document.documentElement.scrollTop:页面滚动位置距离顶部距离
window.scrollTo(0,0):让页面滚动条返回至顶部
第一个数字表示x坐标,第二个表示y坐标
<style>
button{
position: fixed;
right: 100px;
bottom: 100px;
display: none;
}
body{
height: 2000px;
}
</style>
</head>
<body>
<h1>hello</h1>
<button>↑</button>
<script>
let btn=document.querySelector("button");
btn.οnclick=function(){
window.scrollTo(0,0);
}
let timer=null;
window.οnscrοll=function(){
if(timer!=null){
clearTimeout(timer);
}
timer=setTimeout(()=>{
console.log("hello")
if(document.documentElement.scrollTop>0){
btn.style.display="block";
}else{
btn.style.display="none";
}
timer=null;
},500)
}
利用闭包封装防抖算法
<style>
button{
position: fixed;
right: 100px;
bottom: 100px;
display: none;
}
body{
height: 2000px;
}
</style>
</head>
<body>
<h1>hello</h1>
<button>↑</button>
<script>
let btn=document.querySelector("button");
btn.οnclick=function(){
window.scrollTo(0,0);
}
let timer=null;
//利用闭包封装防抖算法
function debounce(fn){
let timer=null;
function eventFun(){
if(timer!=null){
clearTimeout(timer);
}
timer=setTimeout(()=>{
fn();
//业务代码
timer=null;
},500)
}
return eventFun
}
window.οnscrοll=debounce(()=>{
console.log("计数器")
if(document.documentElement.scrollTop>0){
btn.style.display="block";
}else{
btn.style.display="none";
}
});
</script>
利用节流封装防抖算法
<style>
button{
position: fixed;
right: 100px;
bottom: 100px;
display: none;
}
body{
height: 2000px;
}
</style>
</head>
<body>
<h1>hello</h1>
<button>↑</button>
<script>
let btn=document.querySelector("button");
btn.οnclick=function(){
window.scrollTo(0,0);
}
let timer=null;
//节流封装防抖算法
function throttle(fn){
let mark=true;
return function(){
if(mark){
setTimeout(() => {
fn();
mark=true;
}, 500);
}
mark=false;
}
}
window.οnscrοll=throttle(()=>{
console.log("计数器")
if(document.documentElement.scrollTop>0){
btn.style.display="block";
}else{
btn.style.display="none";
}
});
</script>
十二、BOM
浏览器对象模型
1.BOM对象
(1)window对象(全局对象):全局对象的方法不用写对象名
1)计时器方法
如setTimeout方法使用时语法有:
setTimeout(()=>{},ms),
实际上全部语法为:
window.setTimeout(()=>{},ms)
2)弹出框方法
①alert
<script>
alert("hello")
</script>
②prompt
<script>
prompt("请输入您的名字:","hello")
</script>
可见,第一对引号是提示语句,第二对引号是文本框的内容
<script>
prompt("请输入您的名字:")
</script>
<script>
let str=prompt("请输入您的名字:")
console.log(str)
</script>
在文本框输入内容后点击确定,则控制台会输出该内容,点取消,控制台输出null
③confirm
返回值为布尔值,点击确定返回true,点击取消返回false
<script>
confirm();
</script>
<script>
confirm("是否删除此条记录");
</script>
eg1.猜数字游戏
随机生成1-100的数字,在prompt弹出框中猜数字,提示【大于目标结果】【小于目标结果】【恭喜你回答正确!】
<script>
let target=Math.floor(Math.random()*100+1);
//递归函数
function guessNumber(){
let number=prompt("请输入你猜的数字:");
if(number==target){
alert("恭喜你回答正确!")
}else if(number>target){
alert("猜大了");
guessNumber();
}else if(number<target){
alert("猜小了")
guessNumber();
}
}
guessNumber();
</script>
eg2.制作一个水果列表,删除选中的水果时使用confirm提示是否确认删除
<ul class="fruit-list">
<li>香蕉</li>
<li>苹果</li>
<li>鸭梨</li>
</ul>
<script>
let ul=document.querySelector(".fruit-list");
ul.οnclick=function(e){
let mark=confirm("是否删除该水果");
if(mark){
ul.removeChild(e.target);
}
}
</script>
(2)screen对象包含有关用户屏幕的信息
(3)location对象用于获得当前页面的地址(URL),并把浏览器重定向到新的页面
1)locaton.href 属性返回当前页面的URL
2)locaton.hostname 主机的域名
3)locaton.pathname 当前页面的路径和文件名
4)locaton.port 端口
5)locaton.protocol 协议
(4)history对象包含浏览器的历史
(5)navigator对象包含有关访问者浏览器的信息
navigator.userAgent
访问https.//www.w3cschool.cn/javascript/js-window-screen.html可获取更多浏览器对象的详细信息与用法
十三、原始类型与引用类型
1.赋值的区别
1)原始类型
原始类赋的是值
let str1="xiaoming";
let str2=str1;
str1="hello" ;
console.log(str1);
console.log(str2);
输出str1和str2分别为hello、xiaoming
2)引用类型
引用类型赋的是引用
let obj1={name:"xiaoming"};
let obj2=obj1;
obj1.name="hello";
console.log(obj1.name);
console.log(obj2.name);
输出结果都为hello
2.比较的区别
1)原始类型
比较的是值是否一样
let str1="hello";
let str2="hello";
console.log(str1===str2)
结果为true
2)引用类型
比较的是引用是否指向同一个对象
let obj1={name:"xiaoming"};
let obj2=obj1;
obj1.name="hello";
console.log(obj1===obj2);
结果为true
let obj1={name:"xiaoming"};
let obj2={name:"xiaoming"};
console.log(obj1===obj2);
结果为false
3.传参的区别
1)原始类型
函数内部对外部没有影响
function fun(x){
x=100;
console.log(`x的值是${x}`);
}
let number=10;
fun(number);
console.log(`number的值是${number}`);
虽然将number作为参数传入函数,并修改了它的值,但是,函数里面始终不影响函数外面,故x=100,number=10
2)引用类型
函数内部对外部有影响
let obj={name:"小明"};
function fun(o){
o.name="小红";
console.log(`o的名字是${o.name}`);
}
fun(obj);
console.log(`obj的名字是${obj.name}`);
结果为二者都是小红
4.类型检测
1)原始数据类型检测
使用typeof检测
let num=100;
console.log(typeof(num))
结果为number
注意:使用typeof检测null返回结果为object,所有引用数据类型用typeof检测结果都为object
2)引用数据类型检测
使用instanceof检测
语法:
值 instanceof 类型
若结果为true,说明该引用类型为说检测 类型
let arr=[1,2,3];
let date=new Date();
console.log(arr instanceof Array)
console.log(date instanceof Date)
console.log(reg instanceof RegExp)
console.log([1,2,3] instanceof Array)
console.log(/123/ instanceof RegExp)
console.log(/123/ instanceof Object)
结果都为true
eg1.数组存储学生列表
<input type="text" class="name" placeholder="姓名">;
<input type="text" class="age" placeholder="年龄">;
<button>添加</button>
<script>
let inputName=document.querySelector(".name");
let inputAge=document.querySelector(".age");
let btn=document.querySelector("button");
let arr=[];
let studentList=[];
class Student{
constructor(name,age){
this.name=name;
this.age=age;
}
};
btn.οnclick=function(){
let student=new Student(inputName.value,inputAge.value);
studentList.push(student);
console.log(studentList);
}
</script>
十四、异步编程
1.异步概念
异步可以多条任务线去执行程序,一条任务卡顿不影响其他任务
2.获取数据的方法
<script>
//ajax与服务器通信,异步获取数据
let target="hello";
function getData(){
//异步的函数
setTimeout(()=>{
//return只能返回同步的数据
return target;
},500)
}
//只能通过函数获取数据
let result=getData();
console.log(result);
假设只能通过函数getData()获取数据,则此时setTimeout为异步,而return只能返回同步的数据,故结果为undefined,解决该问题,获取数据有以下方法:
(1)用回调函数获取数据
将函数作为参数,传递给另一个函数
<script>
let target="hello";
//获取数据的方法:回调函数
function getData(fn){
setTimeout(()=>{
fn(target);
},500)
}
//d为fn()里的参数,即target
getData((d)=>{
console.log(d);
})
</script>
结果为hello
(2)用promise对象获取数据
promise为es2015提供的一个内置对象,promise有一个方法then
eg1.下面为promise获取数据的方法
let target= "hello";
//resolve为函数
let p=new Promise((resolve)=>{
setTimeout(()=>{
resolve(target)
},500)
})
p.then((d)=>{
console.log(d);
})
用promise解决上述获取数据问题:
let target="hello";
//获取数据的方法:promise
function getData(){
return new Promise((resolve)=>{
setTimeout(()=>{
resolve(target);
},500)
})
}
let p=getData();
p.then((data)=>{
console.log(data);
})
(3)用async函数解决异步问题
let target="hello";
//获取数据的方法:用async函数解决异步问题
function getData(){
return new Promise((resolve)=>{
setTimeout(()=>{
resolve(target);
},500)
})
}
async function fun(){
let data=await getData();
console.log(data);
}
fun();
await函数有等待的效果,会等得到promise函数获取到的值后再执行后面的语句