搜索
写经验 领红包

es6变量的解构赋值(变量赋值规则)

导语:ES6 - 3、变量的结构赋值

es6 变量的解构赋值(变量赋值规则)

一、数组的解构赋值

// 按位置赋值let [a, b, c] = [1, 2, 3]; // a=1; b=2; c=3// 左侧缺失变量let [ , , c] = [, , ]; // c=caz// 右侧缺少值let [a, b, ...c] = [1]; // a=1; b=undefined; c=[] 注意c 等于 []// 使用... 完全解构出剩余值let [head, ...tail] = [1, 2, 3, 4]; // head=1; tail=[2,3,4]// 设置默认值let [foo = true] = []; // foo=true// ES6 内部使用严格相等运算符(===),判断一个位置是否有值。// 所以,只有当一个数组成员严格等于undefined,默认值才会生效。let [x, y = &39;] = [&39;, undefined]; // x=a; y=b;let [x = 1] = [null]; // x=null;

二、对象的解构赋值

// 普通解构let { foo, bar } = { foo: &39;, bar: &39; }; // foo=foo; bar=bbb // 未定义值解构let {foo} = {bar: &39;}; // foo=undefined// 解构方法const { sin, cos } = Math;const { log } = console;// 变量名和属性名不一致let { foo: baz } = { foo: &39;, bar: &39; }; // 此处定义的变量是baz,baz=aaa// 默认值,严格等于undefined时才会使用默认值const {x, y = 5, z=3} = {x: 1, y=undefined, z=null}; // x=1; y=5; z=null

三、字符串的解构赋值

const [a, b, c, d, e] = &39;; // a=h; b=e; c=l; d=l; e=o// 解构长度let {length : len} = &39;; // len=5

四、数值和布尔值的解构赋值

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

五、函数参数的解构赋值

function add({x, y}){  return x + y;}add({x: 10, y: 20}); // 30// 可以设置默认值function add({x = 1, y = 2}){  return x + y;}add({x: 10}) // 12

本文内容由快快网络小荣创作整理编辑!