Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the new extensions to es6?

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "what are the new extensions of es6", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what are the new extensions of es6?"

Es6 new extensions: 1, allow the parameters of the function to set default values; 2, the new arrow function, you can use the arrow "= >" to define the function, syntax "var function name = (parameters) = > {...}"; 3, the extension element character "...", you can convert an array into a comma-separated sequence of parameters, or some data structures into arrays.

The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer.

New extensions to es6

First, function parameters

ES6 allows you to set default values for the parameters of a function

Function log (x, y = 'World') {console.log (x, y);} console.log (' Hello') / / Hello Worldconsole.log ('Hello',' China') / / Hello Chinaconsole.log ('Hello','') / / Hello

The formal parameters of a function are declared by default and cannot be declared again using let or const

Function foo (x = 5) {let x = 1; / / error const x = 2; / / error}

Parameter default values can be used in combination with default values for deconstructing assignments.

Function foo ({x, y = 5}) {console.log (x, y);} foo ({}) / / undefined 5foo ({x: 1}) / / 1 5foo ({x: 1, y: 2}) / / 1 2foo () / / TypeError: Cannot read property'x'of undefined

The above foo function can be deconstructed only when the parameter is an object. If no parameter is provided, the variables x and y will not be generated, thus reporting an error. Here, set the default value to avoid

Function foo ({x, y = 5} = {}) {console.log (x, y);} foo () / / undefined 5

The default value of the parameter should be the tail parameter of the function. If the non-trailing parameter sets the default value, in fact, this parameter is not omitted.

Function f (x = 1, y) {return [x, y];} f () / / [1, undefined] f (2) / / [2, undefined] f (, 1) / / error f (undefined, 1) / / [1,1]

Second, function attributes

The length property of the function

Length will return the number of parameters that do not specify a default value

(function (a) {}) .length / / 1 (function (a = 5) {}) .length / / 0 (function (a, b, c = 5) {}) .length / / 2

The rest parameter is also not counted in the length attribute

(function (... args) {}) .length / / 0

If the parameter that sets the default value is not a tail parameter, then the length property is no longer counted as a later parameter.

(function (a = 0, b, c) {}) .length / / 0 (function (a, b = 1, c) {}) .length / / 1

Name attribute

Returns the function name of the function

Var f = function () {}; / / ES5f.name / / "/ / ES6f.name / /" f "

If you assign a named function to a variable, the name property returns the original name of the named function.

Const bar = function baz () {}; bar.name / / "baz"

The function instance returned by the Function constructor. The value of the name attribute is anonymous

Name / / "anonymous" (new Function)

The function returned by bind. The value of the name attribute is prefixed with bound.

Function foo () {}; foo.bind ({}). Name / / "bound foo" (function () {}). Bind ({}). Name / / "bound"

Third, the function scope

Once the default value of the parameter is set and the function is declared to initialize, the parameter forms a separate scope

When initialization is complete, the scope disappears. This syntax behavior does not occur when the parameter default value is not set.

In the following example, yroomx forms a separate scope, and x is not defined, so it points to the global variable x

Let x = 1 X function f (y = x) {/ / equivalent to let y = x let x = 2; console.log (y);} f () / / 1

IV. Strict mode

As long as the function argument uses a default value, deconstruction assignment, or extension operator, the function cannot be explicitly set to strict mode, otherwise an error will be reported.

/ / function doSomething (a, b = a) {'use strict'; / / code} / / error const doSomething = function ({a, b}) {' use strict'; / / code}; / / error const doSomething = (... a) = > {'use strict'; / / code}; const obj = {/ / error doSomething ({a, b}) {' use strict'; / / code}

5. Arrow function

Use the arrow (= >) to define the function

Var f = v = > v Bang / equivalent to var f = function (v) {return v;}

If the arrow function does not require arguments or requires more than one parameter, use a parenthesis to represent the parameter section

Var f = () = > 5 var sum / equivalent to var f = function () {return 5}; var sum = (num1, num2) = > num1 + num2;// equals var sum = function (num1, num2) {return num1 + num2;}

If there is more than one statement in the code block portion of the arrow function, enclose them in curly braces and return using the return statement

Var sum = (num1, num2) = > {return num1 + num2;}

If you return an object, you need to wrap the object in parentheses

Let getTempItem = id = > ({id: id, name: "Temp"})

Note:

The this object in the body of a function is the object in which it is defined, not the object in which it is used.

Cannot be treated as a constructor, that is, you cannot use the new command, or an error will be thrown

You cannot use an arguments object, which does not exist in the body of the function. If you want to use it, use the rest parameter instead

The yield command cannot be used, so the arrow function cannot be used as a Generator function

VI. Extension operator

ES6 converts an array to a comma-separated sequence of parameters by extending the element character, such as the inverse operation of the rest parameter.

Console.log (. [1, 2, 3]) / / 12 3console.log (1,... [2, 3, 4], 5) / / 1 2 3 4 5 [. Document.querySelectorAll ('p')] / / [

]

Mainly used for function calls, changing an array into a sequence of parameters

Function push (array,... items) {array.push (.. items);} function add (x, y) {return x + y;} const numbers = [4,38]; add (... items) / / 42

You can convert some data structures to arrays

[... document.querySelectorAll ('p')]

It is easier to implement array replication.

Const A1 = [1prime2]; const [... a2] = a1lemacacter / [1mem2]

Array merging is also more concise.

Const arr1 = ['averse,' b']; const arr2 = ['c']; const arr3 = ['dbath,' e']; [. Arr1,... arr2,... arr3] / / ['averse,' baked, 'cased,' dumped,'e']

Note: the shallow copy is implemented through the extension operator, and if the value pointed to by the reference is modified, it will be reflected in the new array synchronously.

It is much clearer to look at an example below.

Const arr1 = ['axiangjiaozhongbao, [1jing2]]; const arr2 = [' c']; const arr3 = [. Arr1,...arr2] arr1 [2] [0] = 9999 / / modify the value of array members in arr1 console.log (arr3) / / affect arr3, ['axiaozhongjiaoyingbao, [999999L2],' c']

Extension operators can be combined with deconstruction assignments to generate arrays

Const [first,... rest] = [1,2,3,4,5]; first / / 1rest / / [2,3,4,5] const [first,... rest] = []; first / / undefinedrest / / [] const [first,... rest] = ["foo"]; first / / "foo" rest / / []

If the extension operator is used for array assignment, it can only be placed in the last bit of the parameter, otherwise an error will be reported.

Const [... butLast, last] = [1,2,3,4,5]; / / error const [first,... middle, last] = [1,2,3,4,5]; / / error report

You can turn a string into a real array

[... 'hello'] / / ["h", "e", "l", "l", "o"]

Objects that define the Iterator interface can be converted to a real array using the extension operator

Let nodeList = document.querySelectorAll ('p'); let array = [... nodeList]; let map = new Map ([[1, 'one'], [2,' two'], [3, 'three'],]); let arr = [... map.keys ()]; / / [1,2,3]

If you use the extension operator for an object that does not have an Iterator interface, an error will be reported

Const obj = {a: 1, b: 2}; let arr = [... obj]; / / TypeError: Cannot spread non-iterable object

7. The method of adding constructor

With regard to constructors, the new methods for arrays are as follows:

Array.from ()

Array.of ()

Array.from ()

Turn two types of objects into real arrays: array-like objects and iterable-capable objects (including ES6's new data structures Set and Map)

Let arrayLike = {'0forth:' asides, '1miles:' breadth, '2bands:' cations, length: 3}; let arr2 = Array.from (arrayLike); / / ['averse,' breadth,'c']

You can also accept the second parameter, which is used to process each element and put the processed value into the returned array

Array.from ([1,2,3], (x) = > x * x) / / [1,4,9]

Array.of ()

Used to convert a set of values to an array

Array.of (3pr 11je 8) / / [3pr 11je 8]

When there are no parameters, an empty array is returned

When there is only one parameter, it actually specifies the length of the array

When the number of parameters is not less than 2, Array () will return a new array of parameters.

Array () / / [] Array (3) / / [,] Array (3,11,8) / / [3,11,8]

VIII. Methods for adding instance objects

The new methods for array instance objects are as follows:

CopyWithin ()

Find (), findIndex ()

Fill ()

Entries (), keys (), values ()

Includes ()

Flat (), flatMap ()

CopyWithin ()

Copy the members of the specified location to another location (overwriting the original members), and then return to the current array

The parameters are as follows:

Target (required): replace data from this location. If it is negative, it is reciprocal.

Start (optional): read data from this location, default is 0. If it is negative, it is calculated from the end.

End (optional): stops reading data before reaching that location, which by default equals the length of the array. If it is negative, it is calculated from the end.

[1, 2, 3, 4, 5] .copyWithin (0,3) / / copy the members (4 and 5) from bit 3 to the end of the array to the position starting from bit 0, covering the original 1 and 2 / [4,5,3,4,5]

Find (), findIndex ()

Find () is used to find the first qualified array member

Parameter is a callback function that accepts three parameters as the current value, the current position, and the original array.

[1,5,10,15] .find (function (value, index, arr) {return value > 9;}) / / 10

FindIndex returns the position of the first qualified array member, or-1 if none of the members meet the criteria

[1,5,10,15] .findIndex (function (value, index, arr) {return value > 9;}) / / 2

Both methods accept the second parameter, which is used to bind the this object of the callback function.

Function f (v) {return v > this.age;} let person = {name: 'John', age: 20}; [10,12,26,15] .find (f, person); / / 26

Fill ()

Populate an array with a given value

New Array (7) / / [7,7,7] fill (3) .fill (7) / / [7,7,7]

You can also accept the second and third parameters, which specify the start and end positions of the fill

['await,' baked,'c'] .fill (7, 1, 2) / / ['await, 7,' c']

Note that if the type of padding is an object, it is a shallow copy

Entries (), keys (), values ()

Keys () is the traversal of key names, values () is the traversal of key values, and entries () is the traversal of key-value pairs.

Or (let index of ['asides,' b'] .keys ()) {console.log (index);} / 0Accord / 1for (let elem of ['asides,' b'] .values ()) {console.log (elem);} / / 'aplink /' b'for (let [index, elem] of ['asides,' b'] .keys ()) {console.log (index, elem);} / / 0 "a"

Includes ()

Used to determine whether the array contains a given value

[1, 2, 3] .NaN (2) / / true [1, 2, 3] .NaN (4) / / false [1, 2, NaN] .salary (NaN) / / true

The second parameter of the method indicates the starting position of the search, which defaults to 0

If the parameter is negative, it indicates the position of the reciprocal

[1,2,3] .duration (3,3); / / false [1,2,3] .duration (3,-1); / / true

Flat (), flatMap ()

Flatten the array and return a new array with no effect on the original data

[1,2, [3,4]] .flat () / / [1,2,3,4]

Flat () will only "flatten" one layer by default. If you want to "flatten" the nested array of multiple layers, you can write the parameters of the flat () method as an integer, indicating the number of layers you want to flatten. The default is 1.

[1,2, [3, [4,5]] .flat () / [1,2,3, [4,5]] [1,2, [3, [4,5] .flat (2) / / [1,2,3,4,5]

The flatMap () method executes a function on each member of the original array, which is equivalent to Array.prototype.map (), and then executes the flat () method on the array of return values. This method returns a new array without changing the original array.

/ equivalent to [[2,4], [3,6], [4,8] .flat () [2,3,4] .flatMap ((x) = > [x, x * 2]) / / [2,4,3,6,4,8]

The flatMap () method can also take a second argument to bind the this in the traversal function.

9. The vacancy of the array

The vacancy of an array means that there is no value at a certain position in the array.

ES6 explicitly converts vacancies to undefined, including Array.from, extension operator, copyWithin (), fill (), entries (), keys (), values (), find () and findIndex ().

It is recommended that you avoid empty spaces in your daily writing.

10. Ordering stability

Set sort () to a stable sorting algorithm by default

Const arr = ['peach',' straw', 'apple',' spork']; const stableSorting = (S1, S2) = > {if (S1 [0] < S2 [0]) return-1; return 1;}; arr.sort (stableSorting) / / ["apple", "peach", "straw", "spork"]

In the sorting result, straw is in front of spork, consistent with the original order.

The above is about the content of this article on "what are the new extensions to es6?" I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report