Table of Contents
New extensions in es6
Home Web Front-end Front-end Q&A What new extensions are added to es6?

What new extensions are added to es6?

Apr 11, 2022 pm 05:29 PM
es6

ES6 new extensions: 1. Allow setting default values ​​for function parameters; 2. New arrow function, you can use the arrow "=>" to define the function, the syntax "var function name = (parameter )=>{...}"; 3. The extended element character "..." can convert an array into a parameter sequence separated by commas, and can also convert some data structures into arrays.

What new extensions are added to es6?

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

New extensions in es6

1. Function parameters

ES6Allow default values ​​to be set for function parameters

function log(x, y = 'World') {
  console.log(x, y);
}

console.log('Hello') // Hello World
console.log('Hello', 'China') // Hello China
console.log('Hello', '') // Hello
Copy after login

The formal parameters of functions 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
}
Copy after login

The default value of the parameter can be combined with the default value of the destructuring assignment to use the

function foo({x, y = 5}) {
  console.log(x, y);
}

foo({}) // undefined 5
foo({x: 1}) // 1 5
foo({x: 1, y: 2}) // 1 2
foo() // TypeError: Cannot read property 'x' of undefined
Copy after login

above foo function. Destructuring can only be performed when the parameter is an object. If no parameter is provided, The variables x and y will not be generated and an error will be reported. Set the default value here to avoid

function foo({x, y = 5} = {}) {
  console.log(x, y);
}

foo() // undefined 5
Copy after login

The default value of the parameter should be the tail parameter of the function, if it is not a non-tail parameter The parameter is set to a 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) // 报错
f(undefined, 1) // [1, 1]
Copy after login

2. Function attributes

The length attribute of the function

length will return the number of parameters without a specified default value

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

rest The parameters will not be counted in lengthAttributes

(function(...args) {}).length // 0
Copy after login

If the parameter with a default value is not the last parameter, then the length attribute will no longer be counted in the following parameters

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

name Attribute

Returns the function name of the function

var f = function () {};

// ES5
f.name // ""

// ES6
f.name // "f"
Copy after login

If a named function is assigned to a variable, the name attribute returns the original name of the named function

const bar = function baz() {};
bar.name // "baz"
Copy after login

FunctionThe function instance returned by the constructor, the value of the name attribute is anonymous

(new Function).name // "anonymous"
Copy after login

bind The returned function, the name attribute value will be prefixed with bound

function foo() {};
foo.bind({}).name // "bound foo"

(function(){}).bind({}).name // "bound "
Copy after login

3. Function scope

Once the default value of the parameter is set, the parameter will form a separate scope when the function is declared and initialized.

This scope will disappear when the initialization is completed. This grammatical behavior will not appear when the parameter default value is not set.

In the following example, y=x will form a separate scope, x will not is defined, so it points to the global variablex

let x = 1;

function f(y = x) { 
  // 等同于 let y = x  
  let x = 2; 
  console.log(y);
}

f() // 1
Copy after login

4. Strict mode

As long as the function parameters use default values, Destructuring assignment, or expansion operator, then the function cannot be explicitly set to strict mode, otherwise an error will be reported

// 报错
function doSomething(a, b = a) {
  'use strict';
  // code
}

// 报错
const doSomething = function ({a, b}) {
  'use strict';
  // code
};

// 报错
const doSomething = (...a) => {
  'use strict';
  // code
};

const obj = {
  // 报错
  doSomething({a, b}) {
    'use strict';
    // code
  }
};
Copy after login

5. Arrow function

Use "arrow" (=>) to define functions

var f = v => v;

// 等同于
var f = function (v) {
  return v;
};
Copy after login

If the arrow function does not require parameters or requires multiple parameters, use a parentheses to represent the parameter part

var f = () => 5;
// 等同于
var f = function () { return 5 };

var sum = (num1, num2) => num1 + num2;
// 等同于
var sum = function(num1, num2) {
  return num1 + num2;
};
Copy after login

If the code block of the arrow function has more than one statement, curly braces must be used to enclose them, and the return statement must be used to return

var sum = (num1, num2) => { return num1 + num2; }
Copy after login

If an object is returned, you need to add Parentheses wrap the object

let getTempItem = id => ({ id: id, name: "Temp" });
Copy after login

Note:

  • The this object in the function body is the object where it is defined, not when used. The object

  • cannot be used as a constructor, that is to say, the new command cannot be used, otherwise an error

  • # will be thrown
  • ##You cannot use the

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

  • The

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

6. Expansion operator

#ES6 uses the expansion element operator..., such as the inverse operation of the rest parameter, to convert a Convert an array into a parameter sequence separated by commas

console.log(...[1, 2, 3])
// 1 2 3

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

[...document.querySelectorAll('p')]
// [<p>, <p>, <p>]
Copy after login

Mainly used when calling functions, convert an array into a parameter sequence

function push(array, ...items) {
  array.push(...items);
}

function add(x, y) {
  return x + y;
}

const numbers = [4, 38];
add(...numbers) // 42
Copy after login

You can convert certain data structures into arrays

[...document.querySelectorAll(&#39;p&#39;)]
Copy after login

Can realize array copying more easily

const a1 = [1, 2];
const [...a2] = a1;
// [1,2]
Copy after login

The merging of arrays is also more concise

const arr1 = [&#39;a&#39;, &#39;b&#39;];
const arr2 = [&#39;c&#39;];
const arr3 = [&#39;d&#39;, &#39;e&#39;];
[...arr1, ...arr2, ...arr3]
// [ &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39; ]
Copy after login

Note: What is achieved through the spread operator is a shallow copy, which modifies the value pointed to by the reference. , will be reflected to the new array synchronously

It will be clearer if you look at the example below

const arr1 = [&#39;a&#39;, &#39;b&#39;,[1,2]];
const arr2 = [&#39;c&#39;];
const arr3  = [...arr1,...arr2]
arr1[2][0] = 9999 // 修改arr1里面数组成员值
console.log(arr3 ) // 影响到arr3,[&#39;a&#39;,&#39;b&#39;,[9999,2],&#39;c&#39;]
Copy after login

The expansion operator can be combined with destructuring assignment to generate an array

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   // []
Copy after login

If the expansion operator is The symbol is used for array assignment and can only be placed at the last bit of the parameter, otherwise an error will be reported

const [...butLast, last] = [1, 2, 3, 4, 5];
// 报错

const [first, ...middle, last] = [1, 2, 3, 4, 5];
// 报错
Copy after login

You can convert the string into a real array

[...&#39;hello&#39;]
// [ "h", "e", "l", "l", "o" ]
Copy after login

defines the iterator interface Objects can be converted into real arrays using the spread operator

let nodeList = document.querySelectorAll(&#39;p&#39;);
let array = [...nodeList];

let map = new Map([
  [1, &#39;one&#39;],
  [2, &#39;two&#39;],
  [3, &#39;three&#39;],
]);

let arr = [...map.keys()]; // [1, 2, 3]
Copy after login

If you use the spread operator for an object without an Iterator interface, an error will be reported

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

七、构造函数新增的方法

关于构造函数,数组新增的方法有如下:

  • Array.from()
  • Array.of()

Array.from()

将两类对象转为真正的数组:类似数组的对象和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)

let arrayLike = {
    &#39;0&#39;: &#39;a&#39;,
    &#39;1&#39;: &#39;b&#39;,
    &#39;2&#39;: &#39;c&#39;,
    length: 3
};
let arr2 = Array.from(arrayLike); // [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]
Copy after login

还可以接受第二个参数,用来对每个元素进行处理,将处理后的值放入返回的数组

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

Array.of()

用于将一组值,转换为数组

Array.of(3, 11, 8) // [3,11,8]
Copy after login

没有参数的时候,返回一个空数组
当参数只有一个的时候,实际上是指定数组的长度
参数个数不少于 2 个时,Array()才会返回由参数组成的新数组

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]
Copy after login

八、实例对象新增的方法

关于数组实例对象新增的方法有如下:

  • copyWithin()
  • find()、findIndex()
  • fill()
  • entries(),keys(),values()
  • includes()
  • flat(),flatMap()

copyWithin()

将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组
参数如下:

  • target(必需):从该位置开始替换数据。如果为负值,表示倒数。
  • start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算。
  • end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算。
[1, 2, 3, 4, 5].copyWithin(0, 3) // 将从 3 号位直到数组结束的成员(4 和 5),复制到从 0 号位开始的位置,结果覆盖了原来的 1 和 2
// [4, 5, 3, 4, 5]
Copy after login

find()、findIndex()

find()用于找出第一个符合条件的数组成员
参数是一个回调函数,接受三个参数依次为当前的值、当前的位置和原数组

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

findIndex返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1

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

这两个方法都可以接受第二个参数,用来绑定回调函数的this对象。

function f(v){
  return v > this.age;
}
let person = {name: &#39;John&#39;, age: 20};
[10, 12, 26, 15].find(f, person);    // 26
Copy after login

fill()

使用给定值,填充一个数组

[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;].fill(7)
// [7, 7, 7]

new Array(3).fill(7)
// [7, 7, 7]
Copy after login

还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置

[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;].fill(7, 1, 2)
// [&#39;a&#39;, 7, &#39;c&#39;]
Copy after login

注意,如果填充的类型为对象,则是浅拷贝

entries(),keys(),values()

keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历

or (let index of [&#39;a&#39;, &#39;b&#39;].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of [&#39;a&#39;, &#39;b&#39;].values()) {
  console.log(elem);
}
// &#39;a&#39;
// &#39;b&#39;

for (let [index, elem] of [&#39;a&#39;, &#39;b&#39;].entries()) {
  console.log(index, elem);
}
// 0 "a"
Copy after login

includes()

用于判断数组是否包含给定的值

[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN) // true
Copy after login

方法的第二个参数表示搜索的起始位置,默认为0
参数为负数则表示倒数的位置

[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
Copy after login

flat(),flatMap()

将数组扁平化处理,返回一个新数组,对原数据没有影响

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

flat()默认只会“拉平”一层,如果想要“拉平”多层的嵌套数组,可以将flat()方法的参数写成一个整数,表示想要拉平的层数,默认为1

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

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

flatMap()方法对原数组的每个成员执行一个函数相当于执行Array.prototype.map(),然后对返回值组成的数组执行flat()方法。该方法返回一个新数组,不改变原数组

// 相当于 [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]
Copy after login

flatMap()方法还可以有第二个参数,用来绑定遍历函数里面的this

九、数组的空位

数组的空位指,数组的某一个位置没有任何值

ES6 则是明确将空位转为undefined,包括Array.from、扩展运算符、copyWithin()、fill()、entries()、keys()、values()、find()和findIndex()

建议大家在日常书写中,避免出现空位

十、排序稳定性

将sort()默认设置为稳定的排序算法

const arr = [
  &#39;peach&#39;,
  &#39;straw&#39;,
  &#39;apple&#39;,
  &#39;spork&#39;
];

const stableSorting = (s1, s2) => {
  if (s1[0] < s2[0]) return -1;
  return 1;
};

arr.sort(stableSorting)
// ["apple", "peach", "straw", "spork"]
Copy after login

排序结果中,straw在spork的前面,跟原始顺序一致

The above is the detailed content of What new extensions are added to es6?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

How to reverse an array in ES6 How to reverse an array in ES6 Oct 26, 2022 pm 06:19 PM

In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

Why does the mini program need to convert es6 to es5? Why does the mini program need to convert es6 to es5? Nov 21, 2022 pm 06:15 PM

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

How to find different items in two arrays in es6 How to find different items in two arrays in es6 Nov 01, 2022 pm 06:07 PM

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

How to implement array deduplication in es5 and es6 How to implement array deduplication in es5 and es6 Jan 16, 2023 pm 05:09 PM

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

What does es6 temporary Zenless Zone Zero mean? What does es6 temporary Zenless Zone Zero mean? Jan 03, 2023 pm 03:56 PM

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

Is require an es6 syntax? Is require an es6 syntax? Oct 21, 2022 pm 04:09 PM

No, require is the modular syntax of the CommonJS specification; and the modular syntax of the es6 specification is import. require is loaded at runtime, and import is loaded at compile time; require can be written anywhere in the code, import can only be written at the top of the file and cannot be used in conditional statements or function scopes; module attributes are introduced only when require is run. Therefore, the performance is relatively low. The properties of the module introduced during import compilation have slightly higher performance.

Is es6 map ordered? Is es6 map ordered? Nov 03, 2022 pm 07:05 PM

The map is ordered. The map type in ES6 is an ordered list that stores many key-value pairs. The key names and corresponding values ​​support all data types; the equivalence of key names is determined by calling the "Objext.is()" method. Implemented, so the number 5 and the string "5" will be judged as two types, and can appear in the program as two independent keys.

See all articles