let
1.let声明的变量只能声明一次,不能被重新定义;
2.let定义的变量必须先定义再使用,不能在声明之前访问该变量;
3.let定义的变量存在块级作用域,不能被变量提升,
4.let在for循环外部不能被使用;所以for循环推荐使用let
const:
const的作用:定义常量
常量不允许重新赋值
const msg=123
msg=456
定义常量时必须进行初始化
const msg =“hello”
常量定义时一般全部大写(这是一种约定,而不是强制的)
const PI=3.14
箭头函数:
function foo(){
console.log(“hello”)
}
等效写法
let foo=()=>{
console.log(“hello”)
}
简化:如果函数体只有一行代码,可简化为如下形式
无参数:let foo=()=>console.log(“hello”)
有参数:let foo =n=>console.log(n)
foo(123)
如果参数只有一个,那么小括号可以省略
多个参数
如果函数体省略了花括号,并且只有一行代码。那么自带返回值
let foo=(a,b)=>a+b
返回值写法:let foo=(a,b)=>{
return a+b
}
let ret=foo(1,2)
console.log(ret)
箭头函数用处:
定时器:
setTimeout(()=>{
console.log(“hello”)
},1000)
数组循环:
var arr=[]
arr.forEach((item,index)=>{
})
arr.forEach((item)=>{
})
//------------------------
app.get(’/data’,function(req,res)={ })
//等效
app.get(’/data’,(req,res)=>{ })
fs.readFile(’./data.txt’,’‘utf-8’,(err,result)=>{ })
// 箭头函数和普通函数的区别
var info=‘nihao’
var obj={
info:‘hello’,
showInfo:function (){
console.log(this.info);//普通函数谁调用指向谁,此时是obj
},
showMsg:()=>{
console.log(this.info);//箭头本身没有this,函数指向window
}
}
obj.showInfo()//hello
obj.showMsg()//nihao