一、函数
1. 函数参数的默认值
- 函数参数的默认值:调用函数的时候传参了,就使用传递的参数;如果没有传参,就用默认值
- 基本用法:
const multiply = {x, y=1} => x * y;
- 默认值的生效条件:
不传参数,或者明确的传递 undefined 作为参数,只有这两种情况下,默认值才会生效
- 默认值表达式:
如果默认值是表达式,默认值表达式是惰性求值的
- 设置默认值的小技巧:
设置函数参数的默认值,最好从参数列表的右边开始设置
2. 箭头函数
(1) 箭头函数
- 箭头函数的书写方式:
(参数) => {函数体}
- 由于此时书写的是一个匿名函数,我们可以用
const/let 函数名 = (参数) => {函数体}
的方式将函数赋值给一个变量,以便通过函数名调用函数
(2) 将一般函数改写成箭头函数
- 声明形式
function fun() {}
- 声明形式 —> 函数表达式形式
const fun = function () {}
- 函数表达式形式 —> 箭头函数
const fun = () => {}
(3) 箭头函数的注意事项
- 单个参数的情况可以省略圆括号:
const/let 函数名 = 参数 => {函数体}
- 无参数或者多个参数的情况不可以省略圆括号
- 单行函数体的情况可以同时省略 {} 和 return :
const add = (x, y) => x + y;
- 多行函数体的情况不能简写
- 箭头函数返回单行对象的情况可以同时省略 {} 和 return,并在对象的 {} 外面加上 () :
const add = (x, y) => ({ value: x + y });
(4) this指向
- 全局作用域中的 this 指向:
console.log(this); //window
- 一般函数(非箭头函数)中的 this 指向:
- 只有在调用函数的时候 this 指向才能确定
- this 指向和函数在哪调用无关,只和谁调用有关
- 直接调用函数
fun();
:
- 严格模式下指向 undefined
- 非严格模式下指向 window(undefined—>window)
- 箭头函数中的this指向:
- 箭头函数没有自己的 this
- 箭头函数中的 this 指向是通过作用域链查找的
(5) 不适用箭头函数的场景
- 不适用作为构造函数
- 不适用需要 this 指向调用对象的时候
- 不适用需要使用 arguments 的时候
3. 剩余参数
- 认识剩余参数
const add = (x, y, ...args) => {};
- 剩余参数的本质:剩余参数永远是个数组,即使没有值,也是空数组
const add = (x, y, ...args) => {
console.log(x, y, args);
};
add(1);
add(1, 2);
add(1, 2, 3, 4, 5);
- 箭头函数的剩余参数:箭头函数的参数部分即使只有一个剩余参数,也不能省略圆括号
const add = (...args) => {};
- 使用剩余参数替代 arguments 获取实际参数:
const add = (...args) => { console.log(args); };
- 剩余参数的位置:剩余参数只能是最后一个参数,之后不能再有其他参数,否则会报错
二、Iterator
1. 认识 Iterator
- 遍历器(迭代器)
Iterator 遍历器是一个统一的遍历方式
- 使用 Iterator
const it = [1, 2][Symbol.iterator]();
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
- Iterator 指的是一个遍历的过程:
Symbol.iterator(可遍历对象的生成方法)—> it(可遍历对象)—> it.next() —> it.next() —> …(直到 done 为 true)
- 一般不会直接使用 Iterator 去遍历,如何更方便的使用 Iterator,我们可以使用 for…of
2. for…of 用法
- for…of 循环只会遍历出那些 done 为 false 时,对应的 value 值
const arr = [1, 2, 3];
for (const item of arr) {
console.log(item);
}
const arr = [1, 2, 3];
for (const item of arr) {
if (item === 2) {
continue;
}
console.log(item);
}
- keys() 得到的是索引的可遍历对象,可以遍历出索引值
const arr = [1, 2, 3];
console.log(arr.keys());
for (const key of arr.keys()) {
console.log(key);
}
- values() 得到的是值的可遍历对象,可以遍历出值
const arr = [1, 2, 3];
for (const value of arr.values()) {
console.log(value);
}
- entries() 得到的是索引+值组成的数组的可遍历对象
const arr = [1, 2, 3];
for (const entries of arr.entries()) {
console.log(entries);
}
3. 原生可遍历与非原生可遍历
- 什么是可遍历:
只要有 Symbol.iterator 方法,并且这个方法可以生成可遍历对象,就是可遍历的
只要可遍历,就可以使用 for…of 循环来统一遍历
- 原生可遍历的有哪些:
1)数组:
for (const item of [1, 2, 3]) { console.log(item); }
2)字符串:
for (const item of 'hi') { console.log(item); }
3)Set:
for (const item of new Set([1, 2])) { console.log(item); }
4)Map
5)arguments
6)NodeList:
for (const elem of document.querySelectorAll('p')) {
console.log(elem);
elem.style.color = 'red'; }
- 非原生可遍历的有哪些:
1)一般的对象:
const person = {
sex