(6)解构赋值的用途
解构赋值的用途
1.交换变量的值
var a = 100; var b = 200; var t; t = a; a = b; b = t; //解构赋值的写法完成【ES6交换变量的值】 var x = 100; var y = 200; [x, y] = [y, x]; console.log(x); console.log(y); 优点1:直观 优点2:一一对应 优点3:节省内存空间(不用多申请变量)
2.从函数返回多个值
//从函数返回多个值_返回一个数组 function fun () { return [1, 2, 3]; }; console.log(fun()[1]); //2 function fun () { return [1, 2, 3]; }; var [x, y, z] = fun(); console.log(x); //1 console.log(y); //2 console.log(z); //3 //从函数返回多个值_返回一个对象 (取值方便可读性更好) function fun () { return { id : '007', name : 'jewave', age : 26 }; }; var { id, name, age} = fun(); console.log(id);//7 console.log(name);//jewave console.log(age);//26 var { id: person_id, name: person_name, age: person_age} = fun(); console.log(person_id); console.log(person_name); console.log(person_age);
3.函数参数的定义
(1)参数是一组有次序的值(通常用其他函数将参数封装成“数组的解构赋值”来解构) fun([100, 200, 300]); function fun ([x, y, z]) { //x = 100; y = 200; z = 300; }; (2)参数是一组无次序的值(通常用其他函数将参数封装成“对象的解构赋值”来解构,例如ajax) fun({id: '007', name: 'jewave', age: 26}); function fun ({id, name, age}) { //id = '007'; name = 'jewave'; age= 26; };
4.提取json数据
var jsonData = { id: '007', name: 'jewave', age: 26, score:{ chinese: 98 } }; //console.log(jsonData); console.log('name is' + jsonData.name); console.log('age is' + jsonData.age); console.log('chinese score is' + jsonData.score.chinese);//98 console.log('ES6'); let { id: number, name, age, score: score } = jsonData; console.log(number); console.log(age); console.log(score.chinese);
5.函数参数的默认值
//之前的写法,以jQ中的ajax为例 jQuery.ajax({ url: '/path/to/file', type: 'POST', dataType: 'xml/html/script/json/jsonp', data: {param1: 'value1'}, complete: function(xhr, textStatus) { //called when complete }, success: function(data, textStatus, xhr) { //called when successful }, error: function(xhr, textStatus, errorThrown) { //called when there is an error } }); //解构赋值写法 jQuery.ajax = function (url, { async = true, beforeSend = function () {}, cache = true, complete = function () {}, crossDomain = false, global = true, //...more config }) { //... do stuff }; //避免了在函数体内再写 var foo = config.foo || 'default foo';
6.遍历Map结构
var map = new Map(); map.set('id','007'); map.set('name','jewave'); consle.log(map); for(let [key, value] of map) { console.log(key + 'is' + value); } //{'id'=>'007','name'=>'jewave'} //id is 007 //name is jewave //获取键名 for(let [key] of map) { console.log(key); } //id //name // //获取键值 for(let [,value] of map) { console.log(value); };
7.输入模块的指定方法
输入模块的指定方法(RequireJS.js框架为例)
const { SoureMapConsumer, SourceNode } = require('source-map');