一、变量的声明
1.1 var & let & const
var没有块级作用域 ,容易变量提升let有块级作用域const有块级作用域 ,声明的变量只能赋值一次。
结论
优先使用 const (声明一些函数和对象) , 希望变量被改变则用 let , 不要用 var
二、解构赋值(主要记3个)
2.1 数组解构
const arr = ["猪八戒", "孙悟空", "沙僧", "唐僧"];
const [a, b, c] = arr;
2.2 对象解构
const obj = {
name: "孙悟空",
age: 18,
gender: "男",
};
const { name, age, gender } = obj;
2.3 交换变量
let num1 = 10;
let num2 = 20;
[num1, num2] = [num2, num1]; // num1 为 20,num2 为 10
三、展开运算符
const arr = [1, 2, 3, 4];
console.log(...arr); //1,2,3,4
const obj = {
name: "孙悟空",
age: 18,
gender: "男",
};
console.log({ ...obj }); //{name: '孙悟空', age: 18, gender: '男'}
/*
* 可以通过 ... 展开一个数组
* */
function fn(a, b, c) {
return a + b + c;
}
const arr = [1, 2, 3];
// 计算数组中三个数字的和
let result = fn(...arr);
// console.log(result);
// const arr2 = [...arr]; // 相当于将arr浅复制给arr2
const arr2 = [7, 8, 9, ...arr, 4, 5, 6];
// console.log(arr2);
const obj = {
name: '孙悟空',
age: 18,
gender: '男'
};
// const obj2 = {...obj}; // 将obj在新的对象中展开,相当于浅复制
const obj2 = {address: '花果山', ...obj, name: '猪八戒',};
console.log(obj2);
四、箭头函数
- 箭头函数没有自己的
arguments,但是可以配合(剩余运算符...args) - 箭头函数没有自己的
this,this是外层作用域的 - 箭头函数不能通过
call、apply、bind绑定this - 箭头函数不能作为构造函数
/*
* 1.箭头函数中没有arguments
* 2.箭头函数中没有自己的this
* - 它的this总是外层作用域的this
* 3.箭头函数中的this无法通过call()、apply()、bind()修改
* 4.箭头函数无法作为构造函数使用
*
* */
function fn(a, b, ...args){
// arguments用来保存函数的实参
// console.log(arguments.length);
console.log(args);
}
const fn2 = (...args)=>{
console.log(args);
};
const fn3 = () => {
console.log(this);
};
const obj = {
hello:()=>{
console.log(this);
}
};
const obj2 = {
hello:function (){
const test = () => {
console.log('-->',this);
};
test();
}
};
obj2.hello();
// new fn3();
五、模块化
- 默认 导出 和 导入
- 命名 导出 和 导入
六、数组中的方法
- map
- filter
- find
- reduce
const arr = [1, 2, 3, 4, 5];
/*
* map()
* - 可以根据原有数组返回一个新数组
* - 需要一个回调函数作为参数,回调函数的返回值会成为新数组中的元素
* - 回调函数中有三个参数:
* 第一个参数:当前元素
* 第二个参数:当前元素的索引
* 第三个参数:当前数组
*
* filter()
* - 可以从一个数组中获得符和条件的元素
* - 会根据回调函数的结果来决定是否保留元素,true保留,false不保留
*
* find()
* - 可以从一个数组中获得符和条件的第一个元素
*
* reduce()
* - 可以用来合并数组中的元素
* - 需要两个参数:
* 回调函数(指定运算规则)
* 四个参数:
* prev 上一次运算结果
* curr 当前值
* index 当前索引
* arr 当前数组
* 初始值
* - 用来指定第一次运算时prev,如果不指定则直接从第二个元素开始计算
* */
let result = arr.map((item) => {
return item + 2;
});
result = arr.map((item, index, array) => {
return item + 2;
});
// console.log(result);
const arr2 = ['孙悟空', '猪八戒', '沙和尚'];
/*
* <li>孙悟空</li>
* <li>猪八戒</li>
* <li>沙和尚</li>
* */
result = arr2.map(item => "<li>" + item + "</li>");
result = arr.filter(item => item % 2 === 0);
result = arr.find(item => item % 2 === 0);
result = arr.reduce((prev, curr, index) => {
console.log(index, prev, curr);
return prev + curr
},0);
console.log(result);
七、其他
- 模板字符串
- 类的定义、类中的this、类的继承、静态属性和方法(static)
- 等等...