ES6新语法

面向对象(class)

/**
 *  Class
 *  万事皆对象
 */

// function Car(options){
//   this.title = options.title;
// }

// Car.prototype.drive = function(){
//   return "Vroom";
// }

// const car = new Car({title:"BMW"});
// // console.log(car);
// // console.log(car.drive());


// // 继承
// function Toyota(options){
//   Car.call(this,options);
//   this.color = options.color;
// }

// Toyota.prototype = Object.create(Car.prototype);
// Toyota.prototype.constructor = Toyota;

// const toyota = new Toyota({color:"red",title:"Focus"});
// console.log(toyota);
// console.log(toyota.drive());


// es6
class Car{
  constructor({title}){
    this.title = title;
  }
  drive(){
    return 'vroom';
  }
}

// const car = new Car({title:"BMW"});
// console.log(car);
// console.log(car.drive());

class Toyota extends Car{
  constructor(options){
    super(options);
    this.color = options.color;
  }
}

const toyota = new Toyota({color:"red",title:"Focus"});

console.log(toyota);
console.log(toyota.drive());

generator生成器(斐波那契数列)

/**
 *  generator生成器 
 *  可以返回多次的函数
 */


//  function* numbers(){
//   yield;
//  }

//  const gen = numbers();

//  console.log(gen.next());
//  console.log(gen.next());


// 斐波那契数列
// function fib(max){
//   var a = 0,b = 1,arr = [0,1];

//   while(arr.length < max){
//     [a,b] = [b,a + b];
//     arr.push(b);
//   }
//   return arr;
// }

// (0,1,1,2,3)

// console.log(fib(5));
// console.log(fib(10));

function* fib(max){
  var a = 0, b = 1, n = 0;
  while (n < max){
    yield a;
    [a,b] = [b, a + b];
    n++;
  }
  return;
}
// var f = fib(10);

// console.log(f.next());
// console.log(f.next());
// console.log(f.next());
// console.log(f.next());
// console.log(f.next());
// console.log(f.next());
// console.log(f.next());
// console.log(f.next());
// console.log(f.next());
// console.log(f.next());
// console.log(f.next());

for(var x of fib(10)){
  console.log(x);
}

generator生成器原理(迭代器实现)

/**
 *  generator生成器
 *  可以返回多次的函数
 */


//  function* numbers(){
//   yield;
//  }

//  const gen = numbers();

//  console.log(gen.next());
//  console.log(gen.next());

// 迭代器还原生成器的结构
// function nameIterator(names){
//   let nextIndex = 0;
//   return {
//     next:function(){
//       return nextIndex < names.length ? 
//              {value: names[nextIndex++],done:false} :
//              {value: undefined,done:true}
//     }
//   }
// }

// const nameArray = ["Henry","Bucky","Emily"];

// const names = nameIterator(nameArray);

// console.log(names.next().value);
// console.log(names.next());
// console.log(names.next());
// console.log(names.next());

// function* sayNames(){
//   yield 'Henry';
//   yield 'Bucky';
//   yield 'Emily';
// }

// const name = sayNames();

// console.log(name.next());
// console.log(name.next());
// console.log(name.next());
// console.log(name.next());


// id自增 (es 生成器)

function* createIds(){
  let index = 1;

  while(true){
    yield index++;
  }
}

const gen = createIds();

// console.log(gen.next().value);
// console.log(gen.next().value);

for(var i = 0; i < 10; i++){
console.log(gen.next().value);
}

generator实战demo(相亲网)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

</head>
<body>

  <div class="container">
    <div class="row">
      <div class="col-md-6 mx-auto text-center">
        <h1 class="mb-3">相亲网</h1>
        <div id="imageDisplay"></div>
        <br>
        <div id="profileDisplay">
        </div>
        <br>
        <button id="next" class="btn btn-dark btn-block">下一个</button>
      </div>
    </div>
  </div>

  <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdn.bootcss.com/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
  <script src="app.js"></script>
</body>
</html>
const data = [
  {
    name: '米斯特吴',
    age: 30,
    gender: '男',
    lookingfor: '女',
    location: '北京',
    image: 'https://randomuser.me/api/portraits/men/82.jpg'
  },
  {
    name: '吴先生',
    age: 32,
    gender: '男',
    lookingfor: '女',
    location: '上海',
    image: 'https://randomuser.me/api/portraits/men/83.jpg'
  },
  {
    name: '李女士',
    age: 24,
    gender: '女',
    lookingfor: '男',
    location: '北京',
    image: 'https://randomuser.me/api/portraits/women/83.jpg'
  }
];

// 迭代器的方法
// function profileIterator(profiles){
//   let nextIndex = 0;

//   return {
//     next: function(){
//       return nextIndex < profiles.length ? 
//              {value: profiles[nextIndex++],done:false} :
//              {value: undefined, done:true}
//     }
//   }
// }

function* profileIterator(){
  yield data[0];
  yield data[1];
  yield data[2];
}

const profiles = profileIterator(data);

// console.log(profiles.next());

// 手动调用
nextProfile();

document.getElementById('next').addEventListener("click",nextProfile);

function nextProfile(){
  const currentProfile = profiles.next().value;
  // console.log(currentProfile);
  if(currentProfile !== undefined){
    document.getElementById('profileDisplay').innerHTML = `
      <ul class="list-group">
        <li class="list-group-item">姓名: ${currentProfile.name}</li>
        <li class="list-group-item">年龄: ${currentProfile.age}</li>
        <li class="list-group-item">位置: ${currentProfile.location}</li>
        <li class="list-group-item">诉求: ${currentProfile.gender} 寻找的目标对象是${currentProfile.lookingfor}性朋友</li>
      </ul>
    `;
    document.getElementById('imageDisplay').innerHTML = `
    <img src="${currentProfile.image}"/>
  `;
  }else{
    window.location.reload();
  }
}

新的数据结构(map)

/** 
 * 数据结构: map
 * 键值对: 与对象不同的是键和值可以是任何类型
 */

 
 const map1 = new Map();

 // 设置key键
 const key1 = 'some string',
       key2 = {},
       key3 = function(){};

 // 为key设置value值
 map1.set(key1,'Value of key1');
 map1.set(key2,'Value of key2');
 map1.set(key3,'Value of key3');

 // 根据key获取对应的value
//  console.log(map1.get(key1),map1.get(key2),map1.get(key3));

 // 获取对应的value数量
//  console.log(map1.size);

 // for...of遍历map1中的key and value
//  for(let [key,value] of map1){
//    console.log(`${key} = ${value}`);
//  }

// only key
// for(let key of map1.keys()){
//   console.log(key);
// }

// only value
// for(let value of map1.values()){
//   console.log(value);
// }

// forEach遍历map1
// map1.forEach((value,key) => {
//   console.log(`${key} = ${value}`);
// })

// 将map1转化为正常的数组
// const keyValueArray = Array.from(map1);
// console.log(keyValueArray);

// 将map1中的key转化为数组
// const keyArray = Array.from(map1.keys());
// console.log(keyArray);

// 将map1中的value值转换为数组
const valueArray = Array.from(map1.values());
console.log(valueArray);

新的数据结构(set)

/** 
 * 数据结构: set
 * 集合: 可以存储任何数据类型,并且是唯一的(不重复的值)
 */

 const set1 = new Set();

 // 往set1中添加数据
 set1.add(100);
 set1.add("A String");
 set1.add({name:"Henry"});
 set1.add(true);
//  set1.add(100); // 不可以重复添加,无作用

//  console.log(set1);

const set2 = new Set([1,true,'string']);
// console.log(set2);

// 计算set1中的数据个数
// console.log(set1.size);

// 检查set中是否拥有对应的值
// console.log(set1.has(100));
// console.log(set1.has(50 + 50));

// console.log(set1.has({name:"Henry"}));//  匹配的是地址
// console.log({name:"Henry"} === {name:"Henry"});

// 删除set中的内容
set1.delete(100);
// console.log(set1);

// for ... of 遍历set
// for(let item of set1){
//   console.log(item);
// }

// forEach 遍历
// set1.forEach((value) =>{
//   console.log(value);
// })
 

// 将set转换为array
const setArray = Array.from(set1);
console.log(setArray);

王如棋博客
请先登录后发表评论
  • 最新评论
  • 总共0条评论