關於es6 常見問題和基礎知識彙總

一直關注es6的內容 咱們作前端開發的如今少不了對es6知識的瞭解和詳細分析
    1 常見問題
        a . 常見做用塊
     {
       let tel = "13809038724";
       let weiChat  = '13809038724'
       
     }
    {
       function add(...add) {
           let sum = 0;
           for(let val of add){
               sum + = val;
           }
            return sum;
       }
    console.log(add(2,5,3))
    
   }

 2 箭頭函數es6 => 表明大括號

 let f = () =>5;
 let sum = (sum1,sum2 ='2') => sum1+sum2;
 console.log(sum(1,2))
// 箭頭函數對應的是數據整合效果。能夠添加複製
{
   const full = ({first,last}) => first +'last';
   
   //console.log(funll());
   
}
//sperad ... 參數的運算數組用逗號隔開
{
   function push (array,...items){
       array.push(items);
   }
 let number = [4,25];
  console.log(...number);
 
}
{
   let birth = '2014/10/11';
   let perSon = {
       name : birth
   };
   
}
{
   function sayHello (name='world') {
       console.log(`hello`${name})
   }
  sayHello('wayou')
}
{
   function add (...x) {
        return x.reduce((m,n)=>m+n);
       
   }
//console.log(add(1,2,3,4,5,6,7,8,9));
}
{
   let person = ['wuhan','nanjing','hefen'];
   function say(a1,a2,a3){
       console.log(`${a1}${a2}${a3}`)
   }
  say(...person)
}

{
   let s =new Set();
  console.log(a.add(1).add(2).add(3)) // {1,2,3}
   let y = new Map();
   var e = y.set('hello',32);
   
   console.log(y.set(s));
   
}
{

// 不添加劇復的數字
let s  =new Set();
let  vm = new WeakMap();
vm.set(s,{extra:42});

let a= vm.size ===undefined;
console.log(a);

}
{
	//symblos;
	//console.log(Number.EPSILON);//對數
	//console.log(Number.isInteger(Infinity));
	let acosh = Math.hypot(3,4);
	let hypot = Math.acosh(2);
	let imul = Math.imul(Math.pow(2,32)-1 , Math.pow(2,32)-2);
//	console.log('abcde'.contains('cd')); //true
	let as = 'abc'.repeat(3);
	Array.from(document.querySelectorAll('*'));
	Array.of(1,2,3);
	[0,0,0].fill(7,1);
	[1,2,3].findIndex(x =>x ==2); //1
   //['a','b','c'].values();
//   Object.assign(Point,{origin:new Point(0,0)});
  let o =1;
  let k=2;
  let es5={
  	o:o,
  	k:k
  };
  let es6 = {
  	o,
  	k
  };
 // console.log(es5);
 /// console.log(es6);
}
{
   let es5 = {
       hello :function(){
           console.log('hello');
       }
   };
   let es6 = {
       hello (){
            console.log('hello');
       }
   }
console.log(es5.hello());
console.log(es6.hello());

}
{
   let a = 'b';
   let es5 = {
       a:'c',
       b:'c'
   }
let es6 ={
   [a] = 'c'
}
console.log(es5,es6)
   
}
{
   // 新增object API
  // console.log('字符串',Object.is('abc','abc'), 'abc'==='abc');
   // console.log('數組',Object.is([],[]),[]===[]);
  // console.log('拷貝',Object.assign({a:'a'},{b:'b'}));
   let test = {k:123,o:456};
   //  拷貝數組鍵值對
for (let [key,value] of object.entries(test)){
   console.log([key,value]);
}

}
{
     //symbol 概念 做用
	let Symbol1 =Symbol();
	let Symbol2 =Symbol();
	//console.log(Symbol1===Symbol2);
	let a3 = Symbol.for('a3');
	let a4 = Symbol.for('a3');
	//console.log(a3===a4);
     
}
{
	let a1= Symbol.for('abc');
	let obj={
		[a1]:'123',
		'abc':345,
		'c':456
	};
//	console.log(obj);
	for(let [key,value] of Object.entries(obj)){
		//console.log('let ',key,value);
		//拿不到[a1]
		
	}
	//拿到Symbol
	Object.getOwnPropertySymbols(obj).forEach(function(item){
		//console.log(obj[item]);
	});
	//拿到key value
	Reflect.ownKeys(obj).forEach(function(e){
	///	console.log('ownKeys',e,obj[e]);
	})
	
	
}
{
	let list = new Set();
	list.add(5);
	list.add(7);
	//console.log(list.size);
}
{
	let arr =[1,2,3,4,5,'2'];
	let list2= new Set(arr);
	//console.log(list2);
  let sta = ['add','delete','clear','has'];
  let list = new Set(sta);
 // console.log(list.has('add')); //true
 // console.log(list.delete('add'));
 // console.log(list);
 // console.log(list.clear());//清空
// console.log(list);
// for(let key of list.keys()){
// 	  console.log('keys',key);
// }
// for(let value of list.values()){
// 	 console.log('values',value);
// }
// for(let [key,value] of list.entries()){
// 	console.log('en',key,value)
// }
  
}
{
//	console.log("Number",Number.parseFloat === parseFloat);
//	const foo = 'bar';
//	const baz = {foo};
	//baz // {foo:'bar'}
//const baz ={foo:foo};
//	function f(x,y){
//	//	return {x,y};
//	}
//	function f(x,y){
//	//	return {x:x,y:y};
//	}
// 數據結構橫向對比 增 查 改 刪
let map = new Map();

let array = [];
map.set('t',1);
array.push({t:1});
//console.log('map-array',map,array);
//查詢
let map_exist = map.has('t'); //true
let array_exist = array.find(item=>item.t);
//console.log('map_exist',map_exist,array);
// 改
map.set('t',2);
array.forEach(item=>item.t?item.t=2:'');
//console.log('map-array-modify',map,array);
//刪除
map.delete('t');
let index = array.findIndex(item=>item.t);
array.splice(index,1);
//console.log('map',map,array);

//set array
let set = new Set();
let arr =[];
//增
set.add({name:"shulonghu"});
arr.push({name:'shulonghu'});

//console.log('set-updet',set,arr);

//查
 let set_ex = set.has({name:'shulonghu'});
 let arr_ex = arr.find(item=>item.name);
// console.log('set_ex',set_ex,arr_ex);

//改
set.forEach(item=>item.name?item.name=2:'');
arr.forEach(item=>item.name?item.name=2:'')
//console.log('set-array',set_ex,arr_ex);
//刪
set.forEach(item=>item.name?set.delete(item):'');
let indee = arr.findIndex(item=>item.name);
arr.splice(indee,1);
//console.log('/set-arr-empty',set,arr);
}
{
	//map set obj
	let item = {t:1}
	let map =new Map();
	let set =new Set();
	let Obj ={};

	//增
	map.set('t',1);
	set.add(item);
	set.add(item);
	map.set('t',1);
	Obj['t']=1;

   
  //console.info('map-set-obj',Obj,map,set)
	//查
   // console.info({
   // 	'map':map.has('t'),
   // 	'set':set.has('t'),
   // 	'Obj':'t' in Obj //查詢
   //  });

   //改
   map.set('t',2);
   item.t=2;
   Obj['t']= 2;
  // console.info('mso-modify',Obj,map,set);
  // 刪
  map.delete('t');
  set.delete(item); //
  delete Obj['t'];
 // console.info('mso-del',Obj,map,set);
  
  //數據結構 優先考慮map
  

}
{
	//場景
   let obj = {
   	time:'2017-03-11',
   	name:'nat',
   	_r:123
   };

     let monitro = new Proxy(obj, {
        get(target,key){
        return target[key].replace('2017','2018');
       },
       set(target,key,value){
   	if(key==='name'){
   		return target[key]=value;
   	}else{
   		return target[key];
   	}
     },
     has(target,key){
     	if(key==='name'){
     		return target[key]
     	}else{
     		false;
     	}
     },
     // 攔截object.keys object.getOwnPropertySymbols,Object.getOwnPropertyNames
     
   });
   //設置


   
   //讀取
   console.info(monitro.time);
   monitro.time='2018';
   monitro.name='shulonghu';
   //console.log('set',monitro.time,monitro);
   console.log('has','name' in monitro,'time' in monitro) 
   
    delete  monitro.time;
    console.log('delete(key)',monitro);
    delete monitro._r;
    console.log('vm.$delete(key)',monitro);
    delete monitro.name;
    console.log('deletename',monitro)

}
{
	let obj ={
		time:'2017-03-11',
		name:'net',
		_r:123
	};
	console.log('Reflect get ',Reflect.get(obj,'time'));
	Reflect.set(obj,'name','mukewang');
	console.log(obj);
	console.log('has',Reflect.has(obj,'name'));
}
{
	/**
	function validator(target,validator){
		return new Proxy(target,{
			_validator:validator,
			set(target,key,value,proxy){
				if(target.hasOwnProperty(key)){
					let va = this._validator[key];
                  if(!!va(value)){
                  	return Reflect.set(target,key,value,proxy)
                  }else{
                  	 throw Error(`不能設置${key}到${value}`)
                  }
				}else{
					throw Error(`${key} 不存在`)
				}
			}
		});
	}**/

	const personValidators={
		name(val){
			return typeof val==='string'
		},
		age(val){
         return typeof val ==='number' && val>18
		}
	}

	//class Person {
		// constructor(name,age) {
		// 	// code
		// 	this.name=name;
		// 	this.age=age;
		// 	return validator(this.personValidators)
		// }	
	//}

	// const person = new Person('lilei',30);
//    console.info(person);

//    person.name='Han mei mei';
//    console.log(person);
}

{
	/**
	 * 基本語法 類的繼承
	 * 靜態方法 靜態屬性
	 * getter setter
	 */
	//基本定義的實列
	class Parent{
		constructor(name='shulonghu'){
			this.name=name
		}
	}
	let v = new Parent('v1');
	console.log('構造函數和實咧',v);
  
}
{
	class Parent{
		constructor(name='shulonghu'){
			this.name=name
		}
	}
	class Child extends Parent{
      constructor(name='child'){
        super(name); //添加方法
        this.type='child';
        this.age='23';
        this.key='123';
      }
	}
	console.log('繼承',new Child());
	//子類有父類的方法和屬性
	//子類傳遞父類的方法
}
{
  class Parent{
		constructor(name='shulonghu'){
			this.name=name
		}
	 get longName(){
     return 'mk'+this.name
	}
	 set longName(value){
		this.name=value;
	  }
	}
  let v = new Parent();
  console.log(v.longName);
  //添加屬性
  v.longName = 'hello world';
  console.log('setter',v.longName);
  
}
{
	//靜態方法的調用
	 class Parent{
		constructor(name='shulonghu'){
			this.name=name
		}
    static tell(){ //私有成員不能被調用  類的調用,不能用實力調用
    	console.log('tell');
     }

	}
  //  Parent.tell();  //只能是類的調用
   Parent.type='test';
   console.log('靜態屬性',Parent.type);

}
{
	//es5回調異步過程
	let ajax =function(callback){
		console.log('執行');
      setTimeout(function(){
      	callback&&callback.call()
      },1000);
	};
	ajax(function(){
		console.log('setTimeout1');
	});
}
{

	//es6異步回掉
	let ajax=function(){
		console.log('執行2');
		return new Promise(function(resolve, reject) {
			setTimeout(function(){
               resolve();
			},1000)
		});
	};
	ajax().then(function(){
		console.log('Promise','setTimeout2');
	});
	
}

若是以爲寫得還能夠能夠賞識 小虎 輸入圖片說明 輸入圖片說明前端

相關文章
相關標籤/搜索