ES6学习笔记二(解构赋值、语法糖)

赋值

一、展开语法

1、数组浅拷贝

const arr = [...'ABCDE'];
console.log(arr); // ["A", "B", "C", "D", "E"]


const arr1 = [1, 2];
const arr2 = ['a', ...arr1];
const arr3 = [...arr1, ...arr2];
console.log(arr2);	// ['a', 1, 2]
console.log(arr3);	// [1, 2, 'a', 1, 2]

2、对象浅拷贝

const obj1 = {a: 1, b: 2};
const obj2 = {...obj1, c: 30};
console.log(obj2);         // {a:1, b:2, c:30}
const obj3 = {b: 20, c: 30};
const obj4 = {...obj2, ...obj3};  // 合并对象
console.log(obj4);         // {a:1, b:20, c:30}

3、函数调用时传参

function sum(x, y, z) {
  return x + y + z;
}
const data = [1,2,3];
console.log(sum(...data)); // 6

二、剩余语法

1、函数参数

function fn(name, ...args) {
  console.log(name);  // 基础参数
  console.log(args);  // 剩下的参数组成的数组
}
fn('ES6');
//	'ES6'
//	[]
fn('abcd', 7, 'ES6');
//  "abcd"
//	[7, "ES6"]
解构

一、数组解构

var [a, b] = [10, 20];
console.log(a);   // 10
console.log(b);   // 20


//默认值(对未能取的值的变量赋一个默认值)
let [a=3, b=9] = [1];             // a=3 b=9
let [a, b = 1] = [10, ''];        // a=10, b=''
let [a, b = 1] = [10, undefined]; // a=10, b=1
/*在 ES6 中,判断一个数组中是否有值,使用严格相等运算符(===)来进行断,
 *只有当一个数组成员严格等于 undefined,默认值才会生效。所以第三个 b 
 *使用了默认值。
 */
 let [a = 1] = [null];             // a=null
 //null==undefined 返回的是 true,null===undefined 返回的是 false。所以数组成员是 null,默认值就不会生效。


//交换变量
var a = 1;
var b = 4;
[a, b] = [b, a] // a=4, b=1

//选择性获取值
var [a, , , b] = [10, 20, 30, 40];
console.log(a);   // 10
console.log(b);   // 40

//剩余参数
var [a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a);     // 10
console.log(b);     // 20
console.log(rest);  // [30, 40, 50]

二、对象解构

var obj = { name: 'abcd', age: 7 };
var { name, age } = obj;  // name: abcd, age: 7


var {a = 10, b = 5} = {a: 3};                 // a = 3, b = 5
var {a = 10, b = 5} = {a: 3, b: undefined};   // a = 3, b = 5
var {a = 10, b = 5} = {a: 3, b: null};        // a = 3, b = null


var {a, c, ...rest} = {a: 1, b: 2, c: 3, d: 4}
console.log(a);     // 1
console.log(c);     // 3
console.log(rest);  // { b: 2, d: 4 }

三、字符串解构

const [a, b, c, d, e] = 'ABCDE';
console.log(a);   // "A"
console.log(b);   // "B"
console.log(c);   // "C"
console.log(d);   // "D"
console.log(e);   // "E"


let {length : len} = 'hello';
console.log(len); // 5

欢迎访问我的个人博客

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海面有风

您的鼓励将是我前进的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值