21.let
let用来声明变量,它的用法类似于var,但是所声明的变量,只在let命令所在的代码块内有效
2.let的特点:
1.变量必须先定义后使用:
a = 123;//Cannot access 'a' before initialization(报错)
let a;
分析:虽然a在内存中,但是当你在let a 之前访问a时,根据ECMAScript定义,虚拟机会阻止的访问!
2.变量不能重复定义:
let a = 1;
let a = 2;//Identifier 'a' has already been declared(报错)
分析:a被定义两次,引发冲突。
3.块级作用域:
let a = 666;
console.log(a);//666
{
let a = 123;
console.log(a);//123
}
分析:在该块的范围内,才能使用该变量,且该变量不会消失。
4.暂时性死区:
let a = 2;
{
let a = 1;
console.log(a);//1
}
console.log(a);//2
分析:作用域不同的情况下,当内部变量与外部变量同名时,内部变量屏蔽外部变量
3.const:
const命令用来声明常量,一旦声明,其值就不能改变。也就是只读变量。(只能读,不能改)
4.const的特点:
1.const修饰变量为只读变量
2.const必须先定义后使用
3.不能重复定义
4.块级作用域
5.被const修饰的变量必须初始化
*****注意事项:const修饰的变量名一般大写(习惯而已)
5.this:函数体内的一个内置对象(只能在函数体里使用)
1.this与事件连用:this代表触发该事件的元素
document.onclick = function(){
console.log(this);//document
}
2.与普通函数连用:this代表调用该函数的对象
function fun(){
this.document.write("heihei");
}
window.fun();
上面this代表的就是window。
6.bind:
功能:修改某个函数的this指向
参数:bind(被修改的this指向)
注意事项:bind是函数对象的一个成员函数,通常用来修饰匿名函数
let oBox = document.querySelector("#box");
document.onclick = function(){
this.style.display = "none";
}.bind(oBox);
this就变成了oBox,当点击盒子的时候盒子就会消失(this由document变成了oBox)
7.for....in和for....of的区别:
for.....in:遍历下标
for.....of:遍历元素内容(通常用于遍历与set和map)当为有下标的时候用
let strArr = ["heihei","haha","laowang"];
for(let index in strArr){ //遍历下标
console.log(strArr[index]);
}
for(let t of strArr){ //便利值
console.log(t);
}
8.字符串扩展方法(ES6):判断字符串是否包含在另一个字符串中
1.str.includes(参数):
返回布尔值,表示是否找到了参数字符串。
2.str.startsWith(参数):
返回布尔值,参数是否在源字符串的头部。
3.str.endsWith(参数):
返回布尔值,参数是否在源字符串的尾部。
9.JSON.parse和JSON.stringify
1.json对象->字符串
let json = {"name":"老张","age":28};
let str = JSON.stringify(json);
console.log(str,typeof str);
2.字符串—>json对象
let str = '{"name":"老张","age":28}';
let json = JSON.parse(str);
for(let index in json){
console.log(json[index]);
}
10.箭头函数:匿名函数的另一种写法
let fun = ()=>{
console.log("heihei");
}
fun();
注意事项:
1.当箭头函数只有一个参数时可以省略();
let f1 = a => {
console.log(a);
}
f1(123);
2.当函数体只有一个语句时,可以省略{}
let f2 = a => console.log(a);
f2(456);
3.函数的参数的默认值
function f4(a=999,b=777){
console.log(a,b);
}
f4(123);
//箭头函数的this问题
let obj = {
"name":"老高",
"fun":function(){
console.log(this);
},
//箭头函数是没有this的,它的this是上级代码块的this(说明白就是该箭头函数所在作用域的this)
"fun1":()=>{
console.log(this);
}
}
obj.fun();
obj.fun1();
11.jiegou赋值:
解构赋值解析结构进行赋值
let [x,y,z] = [1,2,3];
console.log(x,y,z);
去掉json对象的前缀:
let json = {
"name":"老王",
"age":888
}
let {name,age} = json;
console.log(name,age);
交换2个变量的值:
let a = 123;
let b = 456;
[a,b] = [b,a];
console.log(a,b);