一、var和let const 对比
var 定义变量 作用域:全局 局部
let 定义变量
const 定义常量
//区别1:新增了一个块级作用域 {}
if(true){
var n=2
}
console.log(n) // 2
if(true){
let n=2
}
console.log(n) // 2
//区别2:var 定义变量 存在变量的默认提升功能 ,let 和const没有
console.log(x) // undefined
var x=2
console.log(x) // Cannot access 'x' before initialization
let x=2
//区别3: var 定义可以重复定义 ,let和const不可以
var x=2
var x=3
console.log(x) // 3
let x=2
let x=3
console.log(x) // Identifier 'x' has already been declared
//区别4:var 定义变量 自动挂载 window对象上 。let和const不会
var x=2
console.log(window.x) // 2
let x=2
console.log(window.x) // undefined
//区别5:let 存在暂时性死区问题
var a=20
if(true){
a=40
console.log(a) // Cannot access 'a' before initialization
let a=50
}
//只要在作用域中,用let定义了变量,就必须在定义后使用,哪怕全局有,也不能用
const http="www.baidu.com" //无法更改的变量
http=123
console.log(http) // Assignment to constant variable
二、箭头函数 function对比问题
1. 传统的函数中, this的指向性不明确,对着环境的变化随之发生变化
箭头函数,this指向性明确 永远指向生产环境
2. function函数 存在提升功能, 箭头函数没有
3. function函数可以作为构造函数,但是箭头函数不可以
4. function函数中 存在 arguments参数集合,箭头函数没有
function show(a,b){
console.log(arguments) //arguments永远保存所有的参数 // [1,2,3,4]
}
let show=(a,b,...args)=>{ //...args rest参数
console.log(args) //保存除了形参之外的所有的参数的数组 // [3,4]
}
show(1,2,3,4)
三、function this的指向性问题
1、在全局定义的函数中 this 指向 window
2、对象方法中的 this 指向这个对象
3、构造函数创建对象的方法中 this 指向 new 出来的实例化对象
4、定时器(异步操作)中匿名方法的 this 指向 window 对象
5、事件处理函数中 this 指向事件源
四、其他概念
1.字符串模板
let str="hello world"
console.log("我们的口号是"+str)
//利用字符串模板来拼接字符串 ``
console.log(`我们的口号是${str}`)
2.数据解构
//解构:将复杂结构中的内容,解构成一个简单结构
let user={
name:"wangyi",
pass:"123",
uimg:"asdasdsa.jpg"
}
// name =user.name
// 解构的写法
// 左侧和右侧的key必须相同
let {name,pass}=user
console.log(name) // wangyi
console.log(pass) // 123
//交换变量内容
let a=20
let b=30;
[a,b]=[b,a]
console.log(a) // 30
console.log(b) // 20
3.对象的简写
let name="wangyi"
let age=21
let user={
name:name,
age:age,
eat:function(){
}
}
//对象可以简写
let user={
name,//name:name
age,
//vue 小程序 react
eat(){
}
}
4.拓展运算符
// ...拓展运算符
// rest参数 ...函数的参数中,参数整合数组 1,2,3 [1,2,3]
// 拓展运算符 展开复杂结构
let arr=[1,2,3]
console.log(arr[0],arr[1],arr[2]) // 1 2 3
console.log(...arr) // 1 2 3
// 合并数组
let goods=[4,5,6]
goods.push(...arr) // 1 2 3
console.log(goods) // [4, 5, 6, 1, 2, 3]
//apply() 将原本展开的参数,用数组方式传递
let result=Math.max(...goods)
console.log(result) // 6
//完美的复制数组
let arr=[1,2,3]
let goods=[...arr]
arr.push(4)
console.log(arr) // [1, 2, 3, 4]
console.log(goods) // [1, 2, 3]
//展开对象
let obj={
a:1,
b:2,
c:3,
d:4
}
let x={
...obj,
e:5
}
console.log(obj) // Object ( a:1 b:2 c:3 d:4 )
console.log(x) // Object ( a:1 b:2 c:3 d:4 e:5 )