ECMAScript6 literacy notes (b)

5. array

  1. map (map)
    //eg1:将原数组中的元素,增大一倍后返回一个新数组
    <script>
      let arr=[12,5,8];
      /*let result=arr.map(function (item){  return item*2;  });*/
      let result=arr.map(item=>item*2);//返回arr数组中各个元素2倍的数组
      alert(result);
    </script>
    
    //eg2: 遍历分数数组中的元素,判断是否满足要求后,映射返回对应的结果
    <script>
      let score=[19, 85, 99, 25, 90];
      // 根据score数组元素内容,处理后生成新的数组格式,判断及不及格
      let result=score.map(item=>item>=60?'及格':'不及格');
      alert(score);  alert(result);
    </script>
  2. reduce (summing the array can be used)
           
  3. filter (Filter)
    <script type="text/javascript">
      let arr=[12,23,5,20,76,59];
      /*根据返回的boolean值。其内部会遍历数组的元素,遍历的元素值给了item
       * 判断元素的是否被过滤。*/
      let result=arr.filter(item=>{ return true;//false; })
    </script>

6. string

  1. string.stratsWith ( "string2"); string whether the string begins with the string string2, returns a boolean value.
    <script>
      let str='git://www.baidu.com/2123123';
      if(str.startsWith('http://')){ //是否以"http://"为开头
        alert('普通网址');
      }else if(str.startsWith('https://')){
        alert('加密网址');
      }else if(str.startsWith('git://')){
        alert('git地址');
      }else if(str.startsWith('svn://')){
        alert('svn地址');
      }else{
        alert('其他');
      }
    </script>
  2. string.endsWith ( "string2"); string whether the string end of the string string2, returns a boolean value.
    <script>
      let str='1.png';
      if(str.endsWith('.txt')){
        alert('文本文件');
      }else if(str.endsWith('.jpg')){
        alert('JPG图片');
      }else{  alert('其他');  }
    </script>
  3. String templates:
    use single quotes back ` and $ {} nested string content of the template.
    <script>
      let title='标题';
      let content=`<div>${title}</div>`;
    </script>

7. Object Inheritance and (object-oriented)

Can build objects like java as in ES6, eg:

<script>
  class User{//ES6特性,实体类
    constructor(name, pass){//构造器
      this.name=name;
      this.pass=pass;
    }
    showName(){  alert(this.name);  }
    showPass(){  alert(this.pass);  } 
  } 
  class VipUser extends User{//子类继承
    constructor(name, pass, level){
      super(name, pass);
      this.level=level;
    }
    showLevel(){  alert(this.level);  }
  }
  var v1=new VipUser('blue', '123456', 3);
  v1.showName();
  v1.showPass();
  v1.showLevel();
</script>

8. JSON

 JSON standard wording: key and value need to use double quotes, and can only use double quotes.

  1. and the values ​​are the same key value may be omitted and the value of value =. eg:
    <script type="text/javascript">
      let a=12;
      let json={a,b:5};//简写了 a: a
    </script>
  2. JSON.stringfy (); json serialization; eg:
    <script type="text/javascript">
      let json={"a":12,"b":15};
      // json对象串行化,url传输时需要encodeURIComponent编码转换
      let str='https://www.baidu.com?data='
    			+encodeURIComponent(JSON.stringfy(json));
    </script>
  3. The JSON.parse (); json string format into JSON object. eg:
    <script type="text/javascript">
      let str='{"a":12,"b":5,"c":"abc"}';
      //json格式的字符串转换成json对象。
      let json=JSON.parse(str);
      console.log(json);
    </script>

     

9. promise asynchronous request format

When optimizing ajax request, the request was successful and failure processing method, optimized code format. eg:
Single ajax request:

<script src="jquery.js" charset="utf-8"></script>
<script>
  //resolve:成功;reject: 失败;
  let p=new Promise(function (resolve, reject){
    $.ajax({
      url: 'data/arr2.txt',
      dataType: 'json',
      success(arr){//请求成功调用resolve函数
        resolve(arr);
      },
      error(err){//请求失败调用reject函数
        reject(err);
      }
    })
  });
  p.then(function (arr){//第一个函数对应resolve
    alert('成功'+arr);
  }, function (err){//第二个函数对应reject
    console.log(err);
    alert('失败了'+err);
  });
</script>

Multiple ajax requests:

<script src="jquery.js" charset="utf-8"></script>
<script>
  //resolve:成功;reject: 失败;
  let p=new Promise(function (resolve, reject){
    $.ajax({
      url: 'data/arr2.txt',
      dataType: 'json',
      success(arr){//请求成功调用resolve函数
        resolve(arr);
      },
      error(err){//请求失败调用reject函数
        reject(err);
      }
    })
  });
  let p2=new Promise(function(resolve,reject){......});
  Promise.all([p1,p2]).then(function(arr){//请求都成功
    let [res1, res2]=arr;
    console.log(res1);  console.log(res2);
  },function(){//所有请求至少一个失败
    alert("p1和p2至少有一个请求失败!")
  })
</script>

Promise.all ()  to handle multiple requests

<script src="jquery.js" charset="utf-8"></script>
<script>
  Promise.all([
    $.ajax({url: 'data/arr.txt', dataType: 'json'}),
    $.ajax({url: 'data/json.txt', dataType: 'json'})
  ]).then(function (results){
    let [arr, json]=results;
    console.log(arr,json);
  }, function (){
    alert('失败了');
  });
</script>

 

10. generator generator

generator based on the use: a function, pause function during operation will occur. Step solution asynchronous operation, the structure optimization function.

Scene: After the request data, the data to be requested, then the next step. Since the request before continuing usually asynchronous, so to do this, a callback function is required, so that the code complexity, and therefore can be suspended by the code generator function, to the data request.

Note the three elements:

  • function Show () {} or function Show () {} or function  * Show () {}; generator function can be declared. 
  • Pause function can be executed, similar to the breakpoint. Using the  yield keyword, yield on the implementation of the latter half of the code is required by () next function to another part of the code continue.
  • In the function generator, without using generatorObj.next () method, the function is not executed.
<script>
  function *show(){
    alert('yield上半部分');
    yield;
    alert('yield下');
  }
  let genObj=show();
  genObj.next();    //执行yield上面的代码
  //genObj.next();    //执行yield下面的代码
</script>

 

yield Description: suspended, without waking up is not executed. Reception parameters, return value may be defined. eg: 

/*eg1:yield传参*/
<script>
  function * show(num1, num2){
    alert(`${num1}, ${num2}`);//ES6的字符串模板
    alert('a');
    let yieldParam=yield;
    alert('b');
    alert(yieldParam);
    return;
  }
  let gen=show(99, 88);
  gen.next(12);//第一个next没法给yield传参,可以理解为还没运行到yield。
  gen.next(5);
</script>



/*eg2: yield返回值——JSON对象*/
<script>
  function * show(){
    alert('a');
    yield 12;//yield返回12,可理解为函数上半部分的返回值,函数未执行结束。
    alert('b');
    return 55;//函数返回值,可理解为函数下半部分的返回值
  }
  let gen=show();
  let res1=gen.next();
  console.log(res1);  //yield的返回内容,json数据{value: 12, done: false}
  let res2=gen.next();
  console.log(res2);  //函数的返回内容,json数据{value: 55, done: true}
</script>

Examples generator

I did not write, are more complex still. I encountered then. Feeling not actually used. Perhaps I was too dishes ......

 

Guess you like

Origin blog.csdn.net/J1014329058/article/details/84452392