ES6自用学习笔记(二)

211 阅读6分钟

ES6 对象

  1. ES6允许对象的属性直接写变量
const age = 12; 
const name = "Amy"; 
const person = {age, name};
等同于:
const person = {age: age, name: name}
  1. Generator 函数,则要在前面加一个星号:
const obj = { 
  * myGenerator() { yield 'hello world'; } 
};
//等同于 
const obj = { 
  myGenerator: function* () { yield 'hello world'; } 
};
  1. 属性名表达式 ES6允许用表达式作为属性名,但是一定要将表达式放在方括号内
const obj = { 
  ["he"+"llo"](){ return "Hi"; } 
} obj.hello();  //"Hi"
  1. 对象的拓展运算符
  • 基本用法
let person = {name: "Amy", age: 15}; 
let someone = { ...person }; 
someone; //{name: "Amy", age: 15}
  • 可用于合并两个对象
let age = {age: 15}; 
let name = {name: "Amy"}; 
let person = {...age, ...name}; 
person; //{age: 15, name: "Amy"}
  1. 对象的新方法 将源对象的所有可枚举属性复制到目标对象中

assign 的属性拷贝是浅拷贝:

let target = {a: 1}; 
let object2 = {b: 2}; 
let object3 = {c: 3}; 
Object.assign(target,object2,object3);
target; // {a: 1, b: 2, c: 3}

ES6数组

创建

  1. Array.of() 将参数中所有值作为元素形成数组。
onsole.log(Array.of(1, 2, 3, 4)); // [1, 2, 3, 4] 
// 参数值可为不同类型 
console.log(Array.of(1, '2', true)); // [1, '2', true]
// 参数为空时返回空数组 
console.log(Array.of()); // []
  1. Array.from() 将类数组对象或可迭代对象转化为数组。
// 参数为数组,返回与原数组一样的数组 
console.log(Array.from([1, 2])); // [1, 2] 
// 参数含空位 
console.log(Array.from([1, , 3])); // [1, undefined, 3]
  1. 转化为可迭代对象
  • 转换 map
let map = new Map(); 
map.set('key0', 'value0'); 
map.set('key1', 'value1'); 
console.log(Array.from(map)); 
// [['key0', 'value0'],['key1', // 'value1']]
  • 转换 set
let arr = [1, 2, 3]; 
let set = new Set(arr); 
console.log(Array.from(set)); // [1, 2, 3]
  • 转换字符串
let str = 'abc'; 
console.log(Array.from(str)); // ["a", "b", "c"]
  1. 查找
  • find() 查找数组中符合条件的元素,若有多个符合条件的元素,则返回第一个元素。
let arr = Array.of(1, 2, 3, 4); 
console.log(arr.find(item => item > 2)); // 3
  • findIndex() 查找数组中符合条件的元素索引,若有多个符合条件的元素,则返回第一个元素索引
let arr = Array.of(1, 2, 1, 3);
// 参数1:回调函数 // 参数2(可选):指定回调函数中的 this 值 
console.log(arr.findIndex(item => item == 2)); // 1
  1. 填充
  • fill()
let arr = Array.of(1, 2, 3, 4); 
// 参数1:用来填充的值 
// 参数2:被填充的起始索引 
// 参数3(可选):被填充的结束索引,默认为数组末尾 
console.log(arr.fill(0,1,2)); // [1, 0, 3, 4]
  • copyWithin()
// 参数1:被修改的起始索引 
// 参数2:被用来覆盖的数据的起始索引 
// 参数3(可选):被用来覆盖的数据的结束索引,默认为数组末尾
console.log([1, 2, 3, 4].copyWithin(0,2,4)); // [3, 4, 3, 4]
  1. 遍历
  • entries() 遍历键值对。
let entries = ['a', 'b'].entries(); 
console.log(entries.next().value); // [0, "a"] console.log(entries.next().value); // [1, "b"]
  • keys() 遍历键名
console.log([...[,'a'].keys()]); // [0, 1]
  • values() 遍历键值。
console.log([...[,'a'].values()]); // [undefined, "a"]
  1. 包含
  2. includes() 数组是否包含指定值。
[1, 2, 3].includes(1); // true
  1. 拍平数组
  • flat()
console.log([1 ,[2, 3]].flat());  // [1, 2, 3]
  • flatMap()
console.log([1, 2, 3].flatMap(n => [n * 2]));  // [2, 4, 6]
  1. 复制数组
let arr = [1, 2], arr1 = [...arr]; 
console.log(arr1); // [1, 2]  // 数组含空位 
let arr2 = [1, , 3], arr3 = [...arr2]; 
console.log(arr3); [1, undefined, 3]

合并数组

console.log([...[1, 2],...[3, 4]]); // [1, 2, 3, 4]

ES6函数

只有在未传递参数,或者参数为 undefined 时,才会使用默认参数,null 值被认为是有效的值传递。

function fn(name,age=17)
{ console.log(name+","+age); } 
fn("Amy",18); // Amy,18
fn("Amy"); // Amy,17

1.不定参数

不定参数用来表示不确定参数个数,形如,...变量名

function f(...values){
  console.log(values.length);
} 
f(1,2);  //2 
f(1,2,3,4);  //4
  1. 箭头函数 参数 => 函数体
var f = v => v; //等价于 
var f = function(a){ return a; } 
f(1); //1

Class类

// 匿名类 
let Example = class {
   constructor(a) { this.a = a; } 
} 
// 命名类 
let Example = class Example {
   constructor(a) { this.a = a; } 
}

属性

  1. prototype
Example.prototype={ //methods }

添加方法

Object.assign(Example.prototype,{ //methods })
  1. 静态属性
class Example { 
  // 新提案 static a = 2; 
} 
// 目前可行写法 
Example.b = 2;
  1. 原型方法
class Example { 
  sum(a, b) {
     console.log(a + b); 
  } 
} 
let exam = new Example(); 
exam.sum(1, 2); // 3
  1. 实例方法
class Example { 
  constructor() {
    this.sum = (a, b) => { console.log(a + b); } 
  } 
}

decorator

function testable(target) {
   target.isTestable = true; 
} 
@testable 
class Example {} 
Example.isTestable; // true

模块

export 与 import

模块导入导

  • export 命令可以出现在模块的任何位置,但必需处于模块顶层。
  • import 命令会提升到整个模块的头部,首先执行。
/*-----export [test.js]-----*/ 
let myName = "Tom"; 
let myAge = 20; 
let myfn = function(){ 
  return "My name is" + myName + "! I'm '" + myAge + "years old." 
} 
let myClass = class myClass { static a = "yeah!"; } 
export { myName, myAge, myfn, myClass }     //导出
/*-----import [xxx.js]-----*/   
import { myName, myAge, myfn, myClass } from "./test.js";    //导入console.log(myfn()); // My name is Tom! I'm 20 years old. console.log(myAge); // 20 
console.log(myName);// Tom console.log(myClass.a );// yeah!

as

export 命令导出的接口名称,须和模块内部的变量有一一对应关系。

/*-----export [test.js]-----*/ 
let myName = "Tom"; 
export { myName as exportName }
/*-----import [xxx.js]-----*/
import { exportName } from "./test.js";
console.log(exportName);// Tom     

使用 as 重新定义导出的接口名称,隐藏模块内部的变量

/*-----export [test1.js]-----*/ 
let myName = "Tom"; 
export { myName }
/*-----export [test2.js]-----*/ 
let myName = "Jerry"; 
export { myName }
/*-----import [xxx.js]-----*/ 
import { myName as name1 } from "./test1.js"; 
import { myName as name2 } from "./test2.js"; 
console.log(name1);// Tom 
console.log(name2);// Jerry

import

不允许在加载模块的脚本里面,改写接口的引用指向

import {a} from "./xxx.js" 
a = {}; // error 

import {a} from "./xxx.js" 
a.foo = "hello"; // a = { foo : 'hello' }
  • 单列: 多次重复执行同一句 import 语句,
  • 静态执行特性:import 是静态执行,所以不能使用表达式和变量。

export

在一个文件或模块中,export、import 可以有多个,export default 仅有一个。

Promise

异步操作有三种状态:pending(进行中)、fulfilled(已成功)和 rejected(已失败)

  • 无法取消 Promise ,一旦新建它就会立即执行,无法中途取消。
  • 如果不设置回调函数,Promise 内部抛出的错误,不会反应到外部。
  • 当处于 pending 状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成
  1. then 收两个函数作为参数,当前运行完成之前,回调函数永远不会被调用
const p = new Promise(function(resolve,reject){ 
   resolve('success'); 
}); 
p.then(function(value){ 
   console.log(value); 
});

Genterator

Generator 有两个区分于普通函数的部分:

  • 一是在 function 后面,函数名之前有个 * ;
  • 函数内部有 yield 表达式。
  • 调用 Generator 函数和调用普通函数一样,在函数名后面加上()即可
  • 但是 Generator 函数不会像普通函数一样立即执行,而是返回一个指向内部状态对象的指针,所以要调用遍历器对象Iterator 的 next 方法,指针就会从函数头部或者上一次停下来的地方开始执行
function* func(){
   console.log("one");
   yield '1'; 
}
  1. next方法
  • next 方法不传入参数的时候,yield 表达式的返回值是 undefined 。
  • next 传入参数的时候,该参数会作为上一步yield的返回值。
  1. return方法
  • return 方法返回给定值,并结束遍历 Generator 函数。
  • return 方法提供参数时,返回该参数;不提供参数时,返回 undefined 。
  1. yield方法 yield* 表达式表示 yield 返回一个遍历器对象
  2. Iterator方法 为不具备 Iterator 接口的对象提供遍历方法。

async

async 是 ES7 才有的与异步操作有关的关键字,和 Promise , Generator 有很大关联的。

  • name: 函数名称。
  • param: 要传递给函数的参数的名称。
  • statements: 函数体语句。
  • async 函数中可能会有 await 表达式,async 函数执行时,如果遇到 await 就会先暂停执行 ,等到触发的异步操作完成后,恢复 async 函数的执行并返回解析值。
async function helloAsync(){ return "helloAsync"; }
async function helloAsync(){ 
  await testAwait(); 
  console.log("helloAsync");
}