让代码更优雅——解构赋值、扩展操作符

为了加深对解构赋值和扩展操作符概念的理解,今天随我来归纳总结一番


沉迷、沉迷。。。

解构赋值

解构赋值可以快速的取得数组或对象中的元素或属性,是ES6里面的新特性

1. 数组解构

1.1 基本变量赋值

let array = [1, 3, 4];
let [a, b, c] = array;
console.log(a); //1
console.log(b); //3
console.log(c); //4

再来看看传统方式赋值

let foo = [4, 8, 0];
let a = foo[0];
let b = foo[1];
let c = foo[2];

注意:两种方式相比之下,解构的方式代码量是不是少很多呢,看起来更简洁呢

1.2 交换变量

let foo = 4;
let bar = 9;
[foo, bar] = [bar, foo];
console.log(foo); //9
console.log(bar); //4

1.3 函数传参解构

let variable = [3, 6];

function test([a, b]){
  console.log(a + b); //9
}

test(variable);

2. 对象解构

2.1 赋值解构

let student = {
    name: 'Daisy',
    age: 23,
    sex: 'girl'
};

let {name, age, sex} = student;
console.log(name); //'Daisy'
console.log(age); //23
console.log(sex); //'girl'

//用新变量名赋值
let {name: a, age: b, sex: c} = student;
console.log(a); // 'Daisy'
console.log(b); //23
console.log(c); //'girl'

2.2 函数传参解构

let student = {
    name: 'Daisy',
    age: 23,
    sex: 'girl'
};

function foo({name, age, sex}){
  console.log(`${name} is ${age} years old`); //'Daisy is 23 years old'
}

foo(student);

3. 字符串解构

let str = 'hello';
let [a, b, c, d, e] = str;
console.log(a); //'h'
console.log(b); //'e'
console.log(c); //'l'
console.log(d); //'l'
console.log(e); //'o'

扩展操作符

在ES6之前想要实现用数组作为参数的情况,采用apply方法

let numArray = [3, 5, 1];
function add(a, b, c){
  console.log(a + b + c);
}

add.apply(null, numArray);

在ES6中有了扩展操作符之后,可以用...实现相同的功能,如下:

let numArray = [3, 5, 1];
function add(a, b, c){
  console.log(a + b + c);
}

add(...numArray);

简单来说就是把一个数组展开成一系列用逗号隔开的值

  • 用于组装数组

let todos = ['todoword'];
let newTodos = [...todos, 'todoletter'] 
console.log(newTodos); //['todoword', 'todoletter']

在此可以引申到rest运算符,与扩展操作符一样是...

  • rest运算符

1.1 获取数组的部分项

let todos = [2, 4, 6, 8];
let [a, n, ...rest] = todos;
console.log(rest); //[6, 8]

1.2 收集函数参数作为数组

function add(first, ...rest){
  console.log(rest); //[5, 7]
}

add(3, 5, 7)

总结:

  • 解构的原理就是等号的两边具有相同的结构,可以取出数组或对象中的元素或属性,减少了用下标逐个取值的麻烦
  • 对于三点运算符,当出现在等号右边时或实参一方时,是扩展运算符,当出现在被赋值的一方或形参一方时,是rest运算符
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 函数参数的默认值 基本用法 在ES6之前,不能直接为函数的参数指定默认值,只能采用变通的方法。 上面代码检查函数l...
    呼呼哥阅读 8,850评论 0 1
  • 三,字符串扩展 3.1 Unicode表示法 ES6 做出了改进,只要将码点放入大括号,就能正确解读该字符。有了这...
    eastbaby阅读 5,449评论 0 8
  • 本文通过学习阮一峰的博客,外加自己的理解,整理了一下我对js变量的解构赋值的理解。 数组的解构赋值 对象的解构赋值...
    宋乐怡阅读 3,418评论 0 2
  • 儿时的睡眠如同嵋邬岭上的甜甜根,满心甜蜜满心欢喜。儿时的睡眠是秋冬时一锅三白汤(预防出血热的食补土方子,白菜白萝卜...
    王宁子阅读 4,574评论 16 10
  • “王木木劈腿了,他给那个女孩发的信息我都看到了,他还背着我去见她,他们是网友……”小舞在电话那头已经泣不成声了。 ...
    麽麽沫阅读 3,146评论 0 0