Giter VIP home page Giter VIP logo

es6's People

Contributors

yongheng2016 avatar

Watchers

 avatar

es6's Issues

Set

Set数组去重

  1. 类似数组,他的成员值都是唯一的,没有重复值

(可以用作数组去重,用setadd方法)

let s = new Set( )
let arr = [2,4,5,6,2,3,5,4,6,3,3,2]
let newArr = []

arr.forEach( val =>s.add(val) )
for (let i of s){
   newArr.push(i)
}
console.log(newArr)  //[ 2, 4, 5, 6, 3 ]
  1. set可以传入一个数组,得到的都是唯一值,可以进行数组去重
let arr = [2,4,5,6,2,3,5,4,6,3,3,2]
let newArr = [...new Set(arr )]  //[ 2, 4, 5, 6, 3 ]
  1. Array的from方法可以将Set结构转化为数组
let arr = [2,4,5,6,2,3,5,4,6,3,3,2]
let newArr = Array.from(new Set(arr))   //[ 2, 4, 5, 6, 3 ]

操作方法和属性

  • add(val) 添加某个值,返回Set结构本身 ( Set { 3, 4, 5, 6 })
  • delete(val) 删除某个值,返回布尔值,表示是否删除成功
  • has(val) 该值是否为Set成员,返回布尔值
  • clear() 清空所有成员,没有返回值
  • Set.prototype.size 返回Set实例的成员总数
  • Set.prototype.constructor 构造函数,默认就是Set函数。

遍历操作

Set的遍历顺序就是插入顺序!!!
Set结构没有键名,所以keys()values()效果相同

  • keys() 返回键名的遍历器对象 (SetIterator { 'red', 'green', 'blue', 'gold' }
  • values() 返回键值的遍历器对象 (SetIterator { 'red', 'green', 'blue', 'gold' }
  • entries() 返回键值对的遍历器对象 (SetIterator { [ 'red', 'red' ], [ 'green', 'green' ], [ 'blue', 'blue' ], [ 'gold', 'gold' ] }
  • forEach() 使用回调遍历每个成员,没有返回值

Set可以间接调用Arraymapfilter方法

所以Set可以很容易实现并集、交集和差级

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);

// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}

// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}

// 差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}

set参考

Generator

ES6 提供的一种异步编程解决方案,函数返回的遍历器对象

function* helloWorldGenerator() {  //不同于普通函数 *号
  yield 'hello';  //yield定义状态
  yield* foo();  //yield* 可以调用另一个Generator函数
  return 'ending';
}

var hw = helloWorldGenerator();


hw.next()
// { value: 'hello', done: false }

hw.next()
// { value: 'world', done: false }

hw.next()
// { value: 'ending', done: true }

hw.next()
// { value: undefined, done: true }

for...of 循环可以不用调用next()方法

function* foo() {
  yield 1;
  yield 2;
  yield 3;
  yield 4;
  yield 5;
  return 6;
}

for (let v of foo()) {
  console.log(v);
}
// 1 2 3 4 5

export

  • 导入模块中的变量
import {variable1, variable2, variable3} form './index.js'

变量variable1, variable2, variable3必须是./index.js模块中存在的变量

  • 将导入模块中的变量重命名 : as
import {variable as newVariable} form './index.js'

newVarialble重命名的变量,除名称外和模块的变量variable作用完全相同

  • 导入的模块可视是相对路径,也可以是绝对路径,.js后缀可以省略
import {variable} form './index.js'  <==>  import {variable} form './index'

但是:如果没有路径,也没有后缀,需要有配置文件告诉js引擎模块的位置

import {variable} form 'index' 擦,这让js引擎怎么找,你需要配置个文件啊
  • import会提升到整个模块头部,所以先引用,import引入不会报错;(类似域var的提升吧)
foo()
import {foo} form './index'
//不会报错,有提升效应
  • import会执行加载的模块,但多次加载只会执行一次
import '../css/index.css'
  • * 导出所有模块
// circle.js

export function area(radius) {
  return Math.PI * radius * radius;
}

export function circumference(radius) {
  return 2 * Math.PI * radius;
}
// main.js

import { area, circumference } from './circle';

console.log('圆面积:' + area(4));
console.log('圆周长:' + circumference(14));

Proxy

用法

var proxy = new Proxy(target, handler);

 - target  拦截的目标对象
 - handler  也是一个对象,用来定制拦截行为

handler对象内方法

拦截某个属性的读取操作

var person = {
  name: "张三"
};

var proxy = new Proxy(person, {
  get: function(target, property) {
    if (property in target) {
      return target[property];  //返回数据
    } else {
      throw new ReferenceError("Property \"" + property + "\" does not exist.");
    }
  }
});

proxy.name // "张三"
proxy.age // 抛出一个错误

拦截某个属性的赋值操作

let validator = {
  set: function(obj, prop, value) {
    if (prop === 'age') {
      if (!Number.isInteger(value)) {  //非整数
        throw new TypeError('The age is not an integer');
      }
      if (value > 200) {
        throw new RangeError('The age seems invalid');
      }
    }

    // 对于满足条件的 age 属性以及其他属性,直接保存
    obj[prop] = value;
  }
};

let person = new Proxy({}, validator);

person.age = 100;

person.age // 100
person.age = 'young' // 报错
person.age = 300 // 报错

拦截函数的调用、call和apply操作

var twice = {
  apply (target, ctx, args) {
    return Reflect.apply(...arguments) * 2;
  }
};
function sum (left, right) {
  return left + right;
};
var proxy = new Proxy(sum, twice);
proxy(1, 2) // 6
proxy.call(null, 5, 6) // 22
proxy.apply(null, [7, 8]) // 30

拦截HasProperty操作,即判断对象是否具有某个属性时,这个方法会生效。典型的操作就是in运算符。

.
.
.
.

关于this

  • Proxy代理的情况下,内部this只想Proxy代理

实例:Web 服务的客户端 (如何使用?)

Proxy 对象可以拦截目标对象的任意属性,这使得它很合适用来写 Web 服务的客户端。

function createWebService(baseUrl) {
  return new Proxy({}, {
    get(target, propKey, receiver) {
      return () => httpGet(baseUrl+'/' + propKey);
    }
  });
}

async

async函数就是将 Generator 函数的星号(*)替换成async,将yield替换成await,仅此而已。

async函数相对于Generator函数的改进:

  • 内置执行器

可以像普通函数一样执行

const asyncReadFile = async function () {
  const f1 = await readFile('/etc/fstab');
  const f2 = await readFile('/etc/shells');
  console.log(f1.toString());
  console.log(f2.toString());
};

asyncReadFile()  //可以像普通函数一样执行
  • 更好的语义

语义化更清楚了

  • 更广的适用性

co模块约定,yield命令后面只能是 Thunk 函数或 Promise 对象,而async函数的await命令后面,可以是 Promise 对象和原始类型的值(数值、字符串和布尔值,但这时等同于同步操作)。

  • 返回值是Promise

返回值是Promise对象,可以用then指定下一步操作

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.