小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
路难行,行路难,一身汗水,满心长。脚下百里路,头顶艳阳天。坚定如磐石,信念似火烧。好男儿,人穷志不缺,天道也酬勤。四方走,走四方,一身是胆,豪气壮。前方坎坷途,千难万般阻。心若有明灯,身似般若行。好男儿,大志存高远,四海皆为家。
解耦赋值是什么
ECMAScript 6 允许按照一定模式从数组或对象中提取值,对变量进行赋值。这种赋值方式被称为“解耦赋值”(Destructuring)。
- ECMAScript 5为变量赋值方式如下:
var a = 10;
var b = 11;
var c = 12;
- ECMAScript 6 为变量赋值方式如下:
let [a, b, c] =[10,11,12];
ECMAScript 6 的“解耦赋值”本质上属于“模式匹配”。赋值运算符两边的模式相同,左边的变量会被赋予对应位置的值。
解耦赋值失败
如果解耦赋值失败的话,变量的值等于undefined。如下代码示例,解耦赋值失败:
let [a]=[];
console.log(a);// undefined
如下代码示例,解耦赋值失败:
let [a, b] = [10];
console.log(b);// undefined
不完全解耦赋值
如果赋值运算符左边的变量的模式只匹配赋值运算符右边数组的一部分的话,则会解耦赋值不完全。但这种情况下,解耦赋值依旧可以成功。
let [x,y]=[1,2,3];
console.log(x, y);
let [a, [b],d]=[1,[2,3], 4];
console.log(a, b, d);
默认值
解耦赋值允许指定默认值。如下代码所示:
let [a = true] = [];
console.log(a);// true
let [m,n = 100] = [10];
console.log(m, n);// 10 100
let [x, y = 100]= [10,undefined];
console.log(x,v):// 10 100
值得注意的是,ECMAScript 6 内部使用全等于运算符判断指定位置是否存在值。所以只有当数组中成员的值等于 undefined 时,默认值才会生效。
对象的解耦赋值
对象的解耦赋值是通过变量名称与对象的属性名称——对应实现的。
let {name, addr}={
name: "海绵宝宝",
addr:"海底"
}
//海绵宝宝海底
console.log(name, addr);
字符串的解耦赋值
字符串的解耦赋值被转换成了类似于数组的对象。
let [a, b, c, d, e,f]= 'wolong';
console.log(a);// w
console.log(b):// o
console.log(c)://l
console.log(d):// o
console.log(e);//n
console.log(f):// g
数值与布尔值的解耦赋值
解耦赋值时,如果赋值运算符右边是数值或布尔值的话,则会先转换为对象。
let {toString: m}= 123;
console.log(m === Number.prototype.toString);// true
let {toString: n} = true;
console.log(n === Boolean.prototype.toString);// true
解耦赋值的规则是,只要赋值运算符右边的值不是对象或数组的话,会先转换为对象。由于 undefined 和 null 无法转换为对象,所以解耦赋值时会报错。
// TypeError: Cannot destructure property 'prop`of 'undefined" or 'null".
let { prop: x }= undefined;
let { prop: y }= null;
函数参数的解耦赋值
声明函数时,函数的参数也可以使用解耦赋值。
function fn([a, b]){
console.log(a, b):// 12
}
fn([1.2]);
交换变量的值
解耦赋值可用于两个变量之间交换值。
let x = 1;
let y = 2;
[x, y]=[y, x];
console.log(x,y):// 2 1
从函数返回多个值
函数一般只能返回一个值。如果想要返回多个值,只能将多个值放置在数组或对象中。如果使用解耦赋值的话,很容易实现函数返回多个值。
//返回一个数组
function example() {
return [1, 2,3];
}
let [a, b, c] = example();
//返回一个对象
function example(){
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();