ES6 完全使用手册

  1. let和const

     默认使用cont ,只有当确实需要改变变量的值的时候才使用let
    // eg:
    var  foo = 'bar'    // bad    
    let   foo = 'bar'  // good 
    const  foo = 'bar'  // better 
    
  2. 模板字符串

    1> 模板字符串
    // eg:
    const  foo = 'this is a'+ example   // bad 
    const foo = `this is a ${example}`   // good 
    2> 标签模板
    // eg:
    let   url = oneLine `www.taobao.com/example/index.html?foo=${foo}&bar=${bar}`   console.log(url)
    let x = 1, y = 2;
    let message = `
    • ${x}
    • ${x + y}
    `; console.log(message); //
    • 1
    • 3
  3. 箭头函数

    优先使用箭头函数,不过一下几种情况避免使用
    1> 使用箭头函数定义对象的方法
    // bad 
    let foo = {value:1,getValue:()=>{console.log(this.value)}}   
    foo.getValue() ;  // undefined
    2>定义原型方法
    // bad
    function Foo(){ this.vlaue = 1}
    Foo.prototype.getValue = ()=>{console.log(this.value)}
    let foo = new Foo()
    foo.getValue() ;   // undefined
    3>作为事件的回调函数
    // bad 
    const button = document.getElementById('myButton');
    button.addEventListener('click',()=>{
    	console.log(this===window)  // true;
    	this.innerHTML = 'Clicked button'
    })
    
  4. Symbol

    //bad 
    const TYPE_AUDIO = 'AUDIO'
    const TYPE_VIDEO = 'VIDEO'
    const TYPE_IMAGE = 'IMAGE'
    
    // good
    const TYPE_AUDIO  = Symbol('AUDIO')
    const TYPE_VIDEO  = Symbol('VIDEO')
    const TYPE_IMAGE = Symbol('IMAGE')
    
  5. Set 和 Map

    1> 数组去重
    [...new Set(Array)]
    2>条件语句的优化
    
    // bad
    function test(color) {
      switch (color) {
        case 'red':
          return ['apple', 'strawberry'];
        case 'yellow':
          return ['banana', 'pineapple'];
        case 'purple':
          return ['grape', 'plum'];
        default:
          return [];
      }
    }
    test('yellow'); // ['banana', 'pineapple']
    
    // good
    const fruitColor = {
      red: ['apple', 'strawberry'],
      yellow: ['banana', 'pineapple'],
      purple: ['grape', 'plum']
    };
    
    function test(color) {
      return fruitColor[color] || [];
    }
    
    // better
    const fruitColor = new Map()
      .set('red', ['apple', 'strawberry'])
      .set('yellow', ['banana', 'pineapple'])
      .set('purple', ['grape', 'plum']);
    
    function test(color) {
      return fruitColor.get(color) || [];
    }
    
  6. for of

    1> 遍历范围
    for... of 循环可以使用的范围包括:
    	a.数组
    	b.Set
    	c.Map
    	d.类数组对象,如arguments对象,DOM Nodelist 对象
    	e.Generator 对象
    	f.字符串
    2>优势
    for (const v of ['a','b','c']){
    	console.log(v)
    }
    // a   b  c
    
    for (const [i,v] of ['a','b','c'].entries()){
    	console.log(i,v)
    }
    // 0 'a' , 1 'b' , 2 'c'
    3>遍历map
    let  map = new Map(arr);
    
    // 遍历key值
    for (let key of map.keys()){
    	console.log(key);
    }
    // 遍历value 值
    for (let value of map.values()){
    	console.log(value);
    }
    // 遍历key和value的值(一)
    for (let item of map.entries()){
    	console.log(item[0],item[1]);
    }
    // 遍历key和 value值 (二)
    for (let [key,value] of data){
    	console.log(key)
    }
    
  7. Promise

    1>基本例子
    // bad
    request (url,function(err,res,body){
    	if(err) handleError(err);
    	fs.writeFile('1.txt',body,function(err){
    		request(url2,function(err,res,body){
    			if(err) handleError(err)
    		})
    	})
    })
    // good
    request(url).then(function(result){
    	return writeFileAsynv('1.txt',result)
    })
    .then(function(result){
    	return request(url2)
    })
    .catch(function(e){
    	handleError(e)
    })
    2>finally
    fetch(file.json).then(data=>data.json())
    .catch(error=>console.error(error))
    .finally(()=>console.log('finished'));
    
  8. Async

    1>代码更加简洁
    // eg1
    // good 
    function fetch(){
    	return (
    		fetchData().then(()=>{return 'done'})
    	)
    }
    // better
    async  function fetch(){
    	await fetchData()
    	return 'done'
    }
    // eg2
    // good
    function fetch(){
    	return fetchData().then(data=>{
    		if(data.moreData){
    			return fetchAnotherData(data).then(moreData=>{
    				return moreData
    			})
    		}else{
    			return data
    		}
    	})
    }
    // better
    async  function fetch(){
    	const data = await fetchData()
    	if(data.moreData){
    		const moreData = await fetchAnoterhData(data);
    		return moreData
    	}else{
    		return data
    	}
    }
    //eg3
    //good
    funciton fetch(){
    	return fetchData().then(value1=>{
    		return fetchMoreData(value2)
    	}).then(value2=>{
    		return fetchMoreData2(value2)
    	})
    }
    // better
    async function fetch(){
    	const value1 = await fetchData()
    	const value2 = await fetchMOreData(value1)
    	return fetchMoreData2(value2)
    }
    2>错误处理
    // good 
    function fetch(){
    	try{
    		fetchData().then(result=>{
    			const data = JSON.parse(result)
    		}).catch((erro)=>{
    			console.log(err)
    		})
    	} 
    	catch(err){
    		console.log(err)	
    	}
    }
    // better
    async function fetch(){
    	try{
    		const data = JSON.parse(await fetchData())
    	}
    	catch(err){
    		console.log(err)
    	}
    }
    
  9. 拓展运算符

    1>arguments 转数组
    // bad
    function sortNumbers(){
    	return Array.prototype.slice.call(arguments).sort();
    } 
    
    // good 
    const sortNumbers = (...numbers)=>numbers.sort();
    
    2>调用函数
    // bad 
    Math.max.apply(null,[14,2,355])
    // good
    Math.max(...[14,3,44])
    3>构建对象
    let [a,b,...arr] = [1,2,3,4,5]
    const {a,b,...others} = {a:1,b:2,c:3,d:4,e:5}
    
    let obj1 = {a:1,b:2}
    let obj2 = {c:3,d:4}
    let merged = {...obj1,...obj2}
    
  10. 数组的拓展方法

    1>keys
       var arr = ["a", , "c"];
       var sparseKeys = Object.keys(arr);
       console.log(sparseKeys); // ['0', '2']
    
       var denseKeys = [...arr.keys()];
       console.log(denseKeys);  // [0, 1, 2]
       
    2> entries
       var arr = ["a", "b", "c"];
       var iterator = arr.entries();
    
       for (let e of iterator) {
       		console.log(e);
       }
    
    
    3>values
       let arr = ['w', 'y', 'k', 'o', 'p'];
       let eArr = arr.values();
    
       for (let letter of eArr) {
     		console.log(letter);
       }
       
    4> includes
        // bad
       function test(fruit) {
         if (fruit == 'apple' || fruit == 'strawberry') {
           console.log('red');
         }
       }
    
       // good
       function test(fruit) {
         const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
         if (redFruits.includes(fruit)) {
           console.log('red');
         }
       }
    
    5> find
       var inventory = [
           {name: 'apples', quantity: 2},
           {name: 'bananas', quantity: 0},
           {name: 'cherries', quantity: 5}
       ];
       
       function findCherries(fruit) {
           return fruit.name === 'cherries';
       }
       
       console.log(inventory.find(findCherries));
       
    6> findIndex
        function isPrime(element, index, array) {
         var start = 2;
         while (start <= Math.sqrt(element)) {
           if (element % start++ < 1) {
             return false;
           }
         }
         return element > 1;
       }
       
       console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
       console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
    

转自链接 https://juejin.im/post/5bfe05505188252098022400

你可能感兴趣的:(前端)