1.let與var的區別
第一种区别:新增块级作用域 每一个 {} 就是一个独特的块级作用域 通过let或者const定义变量 在其内部生效
第二个区别:var定义变量 存在变量的默认提升 let 和const定义的变量 不存在 变量的提升
第三个区别:var定义变量可以重复定义 ,let和const不允许重复
第四个区别:var 定义变量 会被挂载到window上 ,let const不会
第五个区别:let 定义变量存在暫時性死區
2.箭頭函數與function定義函數對比
2.1function函数中,this指向性永远不明确,随着环境随之发生变化;箭头函数中 this的指向性用于指向被定义的环境 专一
function show(){
console.log(this)
}
show() //指向window
let bt1=document.getElementsByTagName("button")[0]
bt1.οnclick=show //this指向button
let obj={
name:"123",
show
}
obj.show() //this指向obj
let show1= ()=>{
console.log(this)
}
let obj1={
name:"123",
show1
}
obj1.show1() //this指向window
2.2function具有默认的提升功能;箭头函数没有
show() //指向window
function show(){
console.log(this)
}
show1() //會報錯
let show1=()=>{
console.log(this)
}
2.3function 可以作为构造函数使用; 箭头函数不行
因為箭頭函數中的this指向不會變,永遠指向它的產生環境
2.4function 中 arguments参数集合;箭头函数中没有 要用拓展運算符
function show(a,b){
console.log(arguments) // 1,2,3,4 --arguments永远保存所有的参数
}
show(1,2,3,4)
let show1=()=>{
console.log(arguments)
}
show1(1,2,3,4) //會報錯
let show=(a,b,...args)=>{ ...args rest参数
console.log(args) //保存除了形参之外的所有的参数的数组
}
3.數據解構
let obj={
name:'王一',
age:21,
height:180
}
//解构:将复杂的结构,简化成 简单结构 ;复杂结构 :对象或者数组;前方结构的变量必须 和复杂结构属性同名
// let {name,age}=obj
//交换变量
let a=20
let b=30;
[a,b]=[b,a]
4.箭頭函數案例
<style>
.box{
width: 300px;
height: 300px;
background-color: red;
}
</style>
<body>
<div class="box"> </div>
<script>
//当点击对应div时,三秒后 让其颜色改成蓝色
//箭頭函數:如果業務中的this指向性,不想發生變化
let box=document.getElementsByClassName("box")[0]
box.οnclick=function(){
//箭頭函數this只會指向產生它的環境
// setTimeout(()=>{
// console.log(this)
// this.style.backgroundColor="blue"
// },3000)
var that=this
//延時器為異步操作,若直接用this會指向window
setTimeout(function(){
that.style.backgroundColor="blue"
},3000)
}
</script>
</body>
5.拓展運算符
5.1用于复杂数据的展开
let arr=[1,2,3]
console.log(...arr) //1,2,3
5.2用于數組合并
let r=[4,5,6]
r.push(...arr)//4,5,6,1,2,3
let arr=[1,2,3]
let x=[0,...arr]
x.push(4)
console.log(...arr)
console.log(x)
let result=Math.max.apply(null,r)
let result=Math.max(...r)
5.3用于引用數據結構
let obj={
a:1,
b:2,
c:3
}
console.log(...obj) //不能直接展开对象
let daobj={
...obj,
d:20
}
console.log(obj)
console.log(daobj)