1

ES6新技术之三点操作符

 1 year ago
source link: https://nakeman.cn/blog/spread-rest-operator-of-es6/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

ES6新技术之三点操作符

ES6 三点操作,包括展开(Spread)和余项(Rest)操作,是对象(实质是字典数据结构 )和数组 编程 语法糖,方便 这些集合的创建,和使用,函数其实是一种抽象的使用。本文简单比较了二者,也是它们的一种技术参考。

ES6 主要改进

1 箭头函数
2 EMS 模块
3 解构赋值
	解构赋值:将结构(数组或字典)内的复值分解出来赋给本地变量
4 块作用域(let const)
5 函数参数默认值
6 扩展操作符
7 余参操作符
8 模板字符串
9 promise
10 类

展开符三点语法(集合展开出子项)

集合(或字典)的编程(创建新集合,或者用集合子项调用函数): Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list.

三个场合:

1 函数(调用)实参

当函数有大量的形式参数,并且需要使用某个数组去调用它:

Function arguments list (myFunction(a, ...iterableObj, b))

function myFunction(v, w, x, y, z) {}
const args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);

2 数组创建

由一个或多个小数组 创建大数组:

Array literals ([1, ...iterableObj, '4', 'five', 6])

const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
//  ["head", "shoulders", "knees", "and", "toes"]

3 对象创建

由一个或多个字典或对象 创建大对象:

Object literals ({ ...obj, key: 'value' })

const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 13 };

const clonedObj = { ...obj1 };
// { foo: "bar", x: 42 }

const mergedObj = { ...obj1, ...obj2 };
// { foo: "baz", x: 42, y: 13 }

扩展符语法设计的意义可以概括为,如果编程任务中,包括对象或数组等可迭代集合的创建,或是函数参数有集合,我直接用集合名,编译自动帮我展开。因为抽象过,简洁易维护。

余项符三点语法(将传来的子项合并为集合)

1 函数(声明)形式参数

如果函数定义的最后一个(形式)参数有余项符(三点...)前缀,那用户调用时提供的“多余”实参将被收集成一个数组,最后的参数就是数组名。余项符语法,为JS提供了创建==不定参数的函数==的能力。

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");

// a, "one"
// b, "two"
// manyMoreArgs, ["three", "four", "five", "six"] <-- an array

2 对象创建

将一大对象解构,用部分属性收集成一个较小的对象

const { a, ...others } = { a: 1, b: 2, c: 3 };
console.log(others); // { b: 2, c: 3 }

3 数组创建

将一大数组解构,用部分项收集成一个较小的数组

const [first, ...others2] = [1, 2, 3];
console.log(others2); // [2, 3]

集合展开符(spread)和集合余项符(rest)最大通用点是 ==三点语法==;其次,是针对可迭代集合的编程(包括函数传值)任务而设计的。

最大的不同,展开符的变量位于等号的右边,展开后创建一个更大的集合(至少是相等);余项符的变量位于等的左边,目的是收集解构传来的部分项,创建一个较小的集合。函数传值时,展开符是实参(类似于等号左边进行估值),展开后实际调用,==简化函数的「对象或数组型的参数」传递==;余项符是形参(类似于等号右边进行赋值),用于收集“余下参数”,实现一种==有不定参数形态的函数==。

这些ES6新语法,一定是基于应用的需要,事务型应用(交互应用)为什么有这么多的 数组,集合,和字典对象的创建(复制,分割)和函数调用?


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK