This article brings you relevant knowledge about javascript, which mainly introduces related issues about the expansion operator. The expansion operator of S6 has a very simple syntax. It uses three The dot sign means "...". You can convert an array into a parameter sequence separated by commas. Let's take a look at it. I hope it will be helpful to everyone.
【Related recommendations: javascript video tutorial, web front-end】
ES6’s expansion operator, Its syntax is very simple, using three periods to represent "...". You can convert an array into a comma-separated sequence of parameters.
It expands the iterable object into its individual elements. The so-called iterable object is any object that can be traversed using a for of
loop, such as: array, string, Map
, Set
, DOM
nodes, etc.
var array = [1,2,3,4]; console.log(...array);//1 2 3 4 var str = "String"; console.log(...str);//S t r i n g
function push(array, ...items) { array.push(...items); } function add(x, y) { return x + y; } const numbers = [4, 38]; add(...numbers) // 42
In the above code, array.push(...items)
and add(...numbers)
These two lines are both function calls, and they both use the spread operator. This operator turns an array into a sequence of parameters.
const arr = [ ...(x > 0 ? ['a'] : []), 'b', ];
If the expansion operator is followed by an empty array, it will have no effect.
[...[], 1] // [1]
There are many other uses of the spread operator...
const m = Math.max(1, 2, 3); //结果为3
But if you want to calculate the maximum value in the array, obviously the array cannot be directly used as a parameter of Math.max(), we need to expand it. Before ES6, we also needed to combine apply to process:
var arr = [2, 4, 8, 6, 0]; function max(arr) { return Math.max.apply(null, arr); } console.log(max(arr));
ES6 can be easily expanded using the spread operator (...). The above example becomes:
var arr = [2, 4, 8, 6, 0]; console.log(Math.max(...arr)); // 3
The expansion operator gives us a new method of merging arrays
// ES5 apply 写法 var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; Array.prototype.push.apply(arr1, arr2); //arr1 [0, 1, 2, 3, 4, 5]
Using the spread operator can easily expand the array into a parameter list
const a1 = [{ foo: 1 }]; const a2 = [{ bar: 2 }]; const a3 = a1.concat(a2); const a4 = [...a1, ...a2]; a3[0] === a1[0] // true a4[0] === a1[0] // true
In the above code, a3
and a4
use two different methods The new arrays are merged, but their members are references to the original array members. This is a shallow copy. If the value pointed to by the reference is modified, it will be reflected in the new array synchronously.
Note: These two methods are shallow copies, so you need to pay attention when using them.
Array is a composite data type. If you copy it directly, you only copy the pointer to the underlying data structure. Not cloning a completely new array.
ES5 can only use workarounds to copy arrays.
const a1 = [1, 2]; const a2 = a1.concat(); a2[0] = 2; a1 // [1, 2]
In the above code, a1
will return a clone of the original array, and modifying a2
will not affect a1
.
The spread operator provides a simple way to copy an array.
//拷贝数组 var array0 = [1,2,3]; var array1 = [...array0]; console.log(array1);//[1, 2, 3] //拷贝数组 var obj = { age:1, name:"lis", arr:{ a1:[1,2] } } var obj2 = {...obj}; console.log(obj2);//{age: 1, name: "lis", arr: {…}}
Remember: the array is still obtained through the pointer, so we do not copy the array itself, we copy just a new pointer.
NodeList
The object is a collection of nodes, usually Returned by properties such asNode.childNodes
and methods such asdocument.querySelectorAll
.
像 NodeList 和 arguments 这种伪数组,类似于数组,但不是数组,没有 Array
的所有方法,例如find
、map
、filter
等,但是可以使用 forEach()
来迭代
可以通过扩展运算符将其转为数组,如下:
const nodeList = document.querySelectorAll(".row"); const nodeArray = [...nodeList]; console.log(nodeList); console.log(nodeArray);
注意:使用扩展运算符将伪数组转换为数组有局限性,这个类数组必须得有默认的迭代器且伪可遍历的
扩展运算符可以与解构赋值结合起来,用于生成数组
// ES5 a = list[0], rest = list.slice(1) // ES6 [a, ...rest] = list
下面是另外一些例子:
const [first, ...rest] = [1, 2, 3, 4, 5]; first // 1 rest // [2, 3, 4, 5] const [first, ...rest] = []; first // undefined rest // [] const [first, ...rest] = ["foo"]; first // "foo" rest // []
注意:如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错。
const [...butLast, last] = [1, 2, 3, 4, 5]; // 报错 const [first, ...middle, last] = [1, 2, 3, 4, 5]; // 报错
ES6的扩展语法可以很简单的把一个字符串分割为单独字符的数组:
[...'hello'] // [ "h", "e", "l", "l", "o" ]
扩展运算符内部调用的是数据结构的 Iterator 接口,因此只要具有 Iterator 接口的对象,都可以使用扩展运算符,比如 Map 结构。
let map = new Map([ [1, 'one'], [2, 'two'], [3, 'three'], ]); let arr = [...map.keys()]; // [1, 2, 3]
Generator 函数运行后,返回一个遍历器对象,因此也可以使用扩展运算符。
var go = function*(){ yield 1; yield 2; yield 3; }; [...go()] // [1, 2, 3]
上面代码中,变量go
是一个 Generator 函数,执行后返回的是一个遍历器对象,对这个遍历器对象执行扩展运算符,就会将内部遍历得到的值,转为一个数组。
如果对没有 Iterator 接口的对象,使用扩展运算符,将会报错。
const obj = {a: 1, b: 2}; let arr = [...obj]; // TypeError: Cannot spread non-iterable object
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of Let's talk about the spread operator in ES6. For more information, please follow other related articles on the PHP Chinese website!