Home  >  Article  >  Web Front-end  >  What features have been enhanced by es6

What features have been enhanced by es6

青灯夜游
青灯夜游Original
2022-11-21 15:36:393732browse

ES6 enhanced functions: 1. Destructuring assignment, allowing values ​​to be extracted from arrays or objects and assigned to variables according to a certain pattern. 2. A traverser interface is added to the string, so that the string can be traversed by a "for...of loop. 3. Template string is an enhanced version of string. 4. Label template is a special form of function call. 5. Set default values ​​for the parameters of the function. 6. This of the arrow function points to the upper-level scope. 7. Allow variables and functions to be written directly inside the curly brackets as attributes and methods of the object.

What features have been enhanced by es6

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

ES6 enhances the original syntax

1, destructuring assignment

#es6 allows following a certain pattern, from an array or Extracting values ​​from an object and assigning values ​​to variables is called destructuring assignment.

Destructuring assignment is simple and easy to understand in code writing, with clear semantics and convenient access to data fields in complex objects.

In destructuring, the source of destructuring is located on the right side of the destructuring assignment expression, and the target of destructuring is on the left side of the destructuring expression.

(1), array Destructuring assignment

ES6 allows extracting values ​​from arrays and objects and assigning values ​​to variables according to certain patterns. This is called destructuring.

let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

let [ , , third] = ["foo", "bar", "baz"];
third // "baz"

let [x, , y] = [1, 2, 3];
x // 1
y // 3

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []

Essentially, this writing method belongs to "Pattern matching", as long as the patterns on both sides of the equal sign are the same, the variable on the left will be assigned the corresponding value.
If the deconstruction is unsuccessful, the value will be equal to undefined. The other case is incomplete deconstruction, that is, the variable on the left of the equal sign The pattern only matches part of the array on the right side of the equal sign. In this case, destructuring can still succeed.

For the Set structure, you can also use the destructuring assignment of the array.

let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"
  • Destructuring assignment allows you to specify a default value.

let [foo = true] = [];
foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
let [x = 1] = [null];x // null

Note that ES6 internally uses the strict equality operator (===) to determine whether a position has a value .So, only when an array member is strictly equal to undefined, the default value will take effect. If an array member is null, the default value will not take effect, because null is not strictly equal to undefined.

function f() {
  console.log('aaa');
}
let [x = f()] = [1];

In the above code, because x can get a value, the function f will not be executed at all. The above code is actually equivalent to the following code.

(2), Destructuring and assignment of objects

There is an important difference between the destructuring of objects and arrays. The elements of the array are arranged in order, and the value of the variable is determined by its position; and The properties of an object are not in order, and the variable must have the same name as the property to get the correct value.

let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined

The destructuring assignment of the object can easily assign the method of the existing object to a variable.

// 例一
let { log, sin, cos } = Math;

// 例二
const { log } = console;
log('hello') // hello

Example 1 of the above code assigns the logarithm, sine, and cosine methods of the Math object to the corresponding variables, which will be much more convenient to use. Example 2 assigns console.log to the log variable.

let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined

In the above code, foo is the matching pattern, and baz is the variable. What is actually assigned is the variable baz, not the pattern foo.
The internal mechanism of object destructuring and assignment is to first find the attribute with the same name and then assign it to the corresponding variable. What is really assigned is the latter, not the former.

Like arrays, destructuring can also be used for objects of nested structures.

let obj = {
  p: [
    'Hello',
    { y: 'World' }
  ]
};

let { p: [x, { y }] } = obj;
x // "Hello"
y // "World"
Default value

Destructuring of an object can also specify a default value.

var {x = 3} = {x: undefined};
x // 3

var {x = 3} = {x: null};
x // null

(3), Destructuring assignment of string

Array-like objects have a length attribute, so this attribute can also be Destructuring assignment.

let {length : len} = 'hello';
len // 5

(4) Destructuring assignment of numerical and Boolean values

When destructuring assignment, if the right side of the equal sign is a numerical value and a Boolean value, then It will be converted into an object first.

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true

(5), destructuring assignment of function parameters

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

add([1, 2]); // 3

(6), purpose

1) Exchange the value of the variable

let x = 1;
let y = 2;
[x, y] = [y, x];

2) Return multiple values ​​​​from the function
The function can only return one value. If you want to return multiple values, you can only return them Put it in an array or object and return it. With destructuring assignments, it is very convenient to retrieve these values.

// 返回一个数组

function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();

// 返回一个对象

function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();

3) Definition of function parameters
Destructuring assignment can easily correspond a set of parameters to variable names.

// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);

// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

4) Extract JSON data
Destructuring assignment is particularly useful for extracting data from JSON objects.

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

console.log(id, status, number);
// 42, "OK", [867, 5309]

5) Traverse the Map structure
Any object deployed with the Iterator interface can be traversed using a for...of loop. The Map structure natively supports the Iterator interface, and with the destructuring and assignment of variables, it is very convenient to obtain key names and key values.

const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world

If you only want to get the key name, or just the key value, you can write it as follows.

// 获取键名
for (let [key] of map) {
  // ...
}
// 获取键值
for (let [,value] of map) {
  // ...
}

2, string enhancement

ES6 加强了对 Unicode 的支持,允许采用\uxxxx形式表示一个字符,其中xxxx表示字符的 Unicode 码点。

"\uD842\uDFB7"
// "?"
"\u20BB7"
// " 7"

ES6 对这一点做出了改进,只要将码点放入大括号,就能正确解读该字符。

(1)字符串的遍历器接口

ES6 为字符串添加了遍历器接口,使得字符串可以被for…of循环遍历。

for (let codePoint of 'foo') {
  console.log(codePoint)
}
// "f"
// "o"
// "o"

(2)模板字符串

模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。

// 普通字符串
`In JavaScript '\n' is a line-feed.`

// 多行字符串
`In JavaScript this is
 not legal.`

console.log(`string text line 1
string text line 2`);

// 字符串中嵌入变量
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

大括号内部可以放入任意的 JavaScript 表达式,可以进行运算,以及引用对象属性。

let x = 1;
let y = 2;

`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"

`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"

let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// "3"

模板字符串之中还能调用函数。如果大括号中的值不是字符串,将按照一般的规则转为字符串。比如,大括号中是一个对象,将默认调用对象的toString方法。

function fn() {
  return "Hello World";
}

`foo ${fn()} bar`
// foo Hello World bar

字符串的新增方法

1,String.fromCodePoint()
ES5 提供String.fromCharCode()方法,用于从 Unicode 码点返回对应字符,但是这个方法不能识别码点大于0xFFFF的字符。

2,String.raw()
ES6 还为原生的 String 对象,提供了一个raw()方法。该方法返回一个斜杠都被转义(即斜杠前面再加一个斜杠)的字符串,往往用于模板字符串的处理方法。

String.raw`Hi\n${2+3}!`
// 实际返回 "Hi\\n5!",显示的是转义后的结果 "Hi\n5!"

String.raw`Hi\u000A!`;
// 实际返回 "Hi\\u000A!",显示的是转义后的结果 "Hi\u000A!"

3, 实例方法:includes(), startsWith(), endsWith()
传统上,JavaScript 只有indexOf方法,可以用来确定一个字符串是否包含在另一个字符串中。ES6 又提供了三种新方法。

includes():返回布尔值,表示是否找到了参数字符串。
startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。

let s = 'Hello world!';

s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true

3,函数的增强

(1)标签模板

标签模板其实不是模板,而是函数调用的一种特殊形式。“标签”指的就是函数,紧跟在后面的模板字符串就是它的参数。

let a = 5;
let b = 10;
function tag(s, v1, v2) {
  console.log(s[0]);
  console.log(s[1]);
  console.log(s[2]);
  console.log(v1);
  console.log(v2);
  return "OK";
}
tag`Hello ${ a + b } world ${ a * b}`;
// "Hello "
// " world "
// ""
// 15
// 50
// "OK"

(2)函数参数增强:参数默认值

ES6 允许为函数的参数设置默认值,即直接写在参数定义的后面。

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

log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello

(3)箭头函数的简化

箭头函数的this指向上级作用域

    const name = 'tony'
    const person = {
      name: 'tom',
      say: () => console.log(this.name),
      sayHello: function () {
        console.log(this.name)
      },
      sayHi: function () {
        setTimeout(function () {
          console.log(this.name)
        }, 500)
      },
      asyncSay: function () {
        setTimeout(()=>console.log(this.name), 500)
      }
    }
    person.say()  //tony
    person.sayHello() //tom
    person.sayHi() //tony
    person.asyncSay()  //tom

4.对象的扩展

属性的简洁表示法

ES6 允许在大括号里面,直接写入变量和函数,作为对象的属性和方法。这样的书写更加简洁。除了属性简写,方法也可以简写。

const foo = 'bar';
const baz = {foo};
baz // {foo: "bar"}

// 等同于
const baz = {foo: foo};
const o = {
  method() {
    return "Hello!";
  }
};

// 等同于

const o = {
  method: function() {
    return "Hello!";
  }
};

1、如果key与value变量名相同,省略:value
2、省略函数:function
3、计算属性:[Math.random()]

   const bar = 'bar'
    const obj = {
      bar,
      fn () {
        console.log('1111')
      },
      [Math.random()]: '123'
    }
    console.log(obj)

【推荐学习:javascript视频教程

The above is the detailed content of What features have been enhanced by es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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