变量的解构赋值

原创
2017/02/17 17:13
阅读数 99

ES6 按照特定的模式,从数组和对象中取值,然后对变量进行赋值,这称之为解构。

 数组的解构赋值

//以前为变量赋值,形式如下
let a = 1;
let b = 2;
let c = 3;
现在,形式如下
let [a,b,c] = [1,2,3]

使用嵌套数组进行解构的例子
let [foo,[[zoo],boo]] = [1,[[2],3]]
//foo = 1
//zoo = 2
//boo = 3
如果结构不成功,变量的值为 undefined
let [foo] = []
foo = undefined
不完全解构
let [a,[b],d] = [1,[2,3],4]
//a = 1;b = 2;d = 4;

解构赋值允许指定默认值
let [x,y='b'] = ['a'] //x = 'a';y='b'
let [x,y = 'b'] = ['a',undefined];//x = 'a';y = 'b'
//如果一个数组成员不严格等于undefined,默认值是不会生效的
let [x = 1] = [undefined] //x = 1
let [x = 1] = [null] //x = null,因为null不严格等于undefined,所以默认值不生效

对象的解构赋值

数组的解构是按照次序来排列的,变量的取值由它的位置而定;对象的属性没有次序,变量必须与属性同名,才能取到正确的值。
let {foo,boo} = {foo:1,boo:2};
//foo=1;boo=2;
let {baz} = {foo:1,boo:2}
//baz = undefined
如果变量名和属性名不一样
var {foo:baz} = {foo:'aaa',bar:'bbb'}

默认值生效的条件,对象的属性值严格等于undefined
var {x = 3} = {x : undefined}
//x = 3;
var {x = 3} = {x : null}
//x = null



字符串的解构赋值

const [a,b,c] = '123'
//a=1;b=2;c=3
let {length,len} = "helloo"
//len = 6

数值和布尔值的解构赋值

let {toString:s} = 123
s === Number.prototype.toString //true
let {toString:s} = true;
s = Boolean.prototype.toString //true
解构赋值的规则是,只要等号右边的值不是对象,先将它转换成对象。由于undefined 和null无法转为对象,所以对它们进行解构赋值,都会报错。
let {prop:x} = undefined;//TypeError
let {prop:y} = undefined;//TypeError

函数参数的解构赋值

function add([x,y]){
  return x + y;
}
add([1,2]);
//3

//undefined 会触发函数参数的默认值
[1,undefined,3].map((x = 'yes')=>x)
//[1,yes,3]

变量解构赋值的作用

交换变量的值
let x = 1;
let y = 2;
[x,y] = [y,x]
从函数返回多个值
function example(){
  return [1,2,3]
}
let [a,b,c] = example();

函数参数的定义
function f([x,y,z]){}.
f([1,2,3])
提取JSON值
let jsonData = {id:1,status:'ok',data:[12,32]};
let {id,status,data} = jsonData;

函数参数的默认值
jQuery.ajax = function(url,{
  async = true,
  beforeSend = function(){},
  cache = true,
  complete = function(){},
  crossDomain = false,
  globle = true,

}){};
遍历Map结构
var map = new Map();
map.set('first','hello');
map.set('second','world');
for(let[key,value] of map){
  console.log(key + " is " + value);

}
//first is hello
//second is world

输入模块的指定方法

const {networkmodule,sourcecode} = require('network')

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部