ES6 New Features Summary

Table of contents

let and const commands

template string

spread operator

destructuring assignment

object deconstruction

array destructuring

Extended functions

Functions with parameter default values

The remaining parameters represent indeterminate parameters

arrow function

extended object

Write variables and functions directly, as properties and methods of objects

新增Object.is()/Object.assign()/Object.keys/Object.value/Object.entries/Object.getOwnPropertyDescriptors方法

extended value

Symbol

Maps and Sets

Set

Map

Iterators and generators/Proxy objects

Promise

class class

Modular implementation


let and const commands

ES6 adds two new keywords for declaring variables : let and const ;

  • There is a variable promotion problem in the var declaration, and there is no variable promotion in let and const
 console.log(a); // undefined 变量提升了 实际代码变为 var a; console.log(a)
 console.log(b); // 报错 Uncaught ReferenceError: Cannot access 'b' before initialization
 console.log(c); // 报错 Uncaught ReferenceError: Cannot access 'c' before initialization
 var a = 120;
 let b = 'false';
 const c = 100;
  • let and const are only accessible at block scope
// 使用var
var arr = [];
  for (var i = 0; i < 10; i++) {
    arr[i] = function() {
      return i
    };
  }
console.log(arr[5]()); // 10


// 使用let或const
const arr = [];
  for (let i = 0; i < 10; i++) {
    arr[i] = function() {
      return i
    };
  }
console.log(arr[5]()); // 5
if(true) {
  var a = 120;
  let b = 'false';
  const c = 100;
}
console.log(a); // 120
console.log(b);  // 报错:Uncaught ReferenceError: b is not defined
console.log(c);  // 报错:Uncaught ReferenceError: c is not defined
  •  Let and const cannot declare variables with the same name in the same scope, but var can
var a = 120;
let b = 'false';
const c = 100;
var a = 130;
let b = 'true'; // Uncaught SyntaxError: Identifier 'b' has already been declared
const c = 200; // Uncaught SyntaxError: Identifier 'c' has already been declared
console.log(a); // 130
  • const can only define constants and cannot be modified 
const b = false;
b = 12;
console.log(b); // Uncaught TypeError: Assignment to constant variable
  • does not pollute global variables
console.log(window.RegExp); // ƒ RegExp() { [native code] }
let RegExp = 10;
console.log(RegExp); // 10 
console.log(window.RegExp); // ƒ RegExp() { [native code] }

template string

Use backticks `` to create template strings, and use ${variable name} when inserting variables;

  let name = '小明';
  let age = '12';
  console.log(name + '今年'+ age + '岁啦!'); // 小明今年12岁啦!
  console.log(`${name}今年${age}岁啦!`); // 小明今年12岁啦!

Using this method can avoid the use of a large number of + and ' ';

spread operator

The spread operator refers to ... , which is used to extend an iterable type or an array;

  • Merge arrays using the spread operator
const arry1 = ['小明', '小红'];
const arry2 = [...arry1, '小李', '小强'];
console.log(arry2); // ['小明', '小红', '小李', '小强']
  • copy array using spread operator
const arry1 = ['小明', '小红'];
const arry2 = [...arry1];
console.log(arry2); // ['小明', '小红']
arry2[2] = '小强';
console.log(arry1, arry2); // ['小明', '小红'] ['小明', '小红', '小强']

The result of copying using the spread operator is not a simple copy of the reference address, so the change will not be affected; 

  • Spread operator with objects
const obj1 = {name: '小明', age: 12};
const obj2 = {hobby: '踢足球'};
const obj3 = {...obj1, ...obj2}
console.log(obj3); // {name: '小明', age: 12, hobby: '踢足球'}

Object extension operator, if the number of layers is 1, it is a deep copy. Levels above the second level are not deep copies;

const obj1 = {name: '小明', age: 12};
const obj2 = {
   project: {
        English: 20,
        huaxue: 30,
       }
};
const obj3 = {...obj1, ...obj2}
console.log(obj3); // {name: '小明', age: 12, hobby: '踢足球'}
obj3.project.huaxue = 90
console.log(obj2); // project: {English: 20, huaxue: 90} obj2的huaxue属性也被改变了
console.log(obj3); // {name: '小明', age: 12, project: {English: 20, huaxue: 90}

destructuring assignment

Destructuring assignment is an extension of the assignment operator, which is a pattern matching for arrays or objects, and then assigning values ​​to the variables in it, which can make the code concise and easy to read;

object deconstruction

 let student = {
    name: '小凡',
    age: 18
 }
 let {name, age} = student
 console.log(name, age); // 小凡 18

 When the object is deconstructed, the variable name on the left should correspond to the key value in the object, use {}

let student = {
  name: '小凡',
  age: 18
}
let {name, age, sex} = student
console.log(name, age, sex); // 小凡 18 undefined

Incomplete deconstruction is also possible;

let student = {
  name: '小凡',
  age: 18,
  sex: '男'
}
let {name} = student
console.log(name); // 小凡

Can be used with the spread operator;

let student = {
  name: '小凡',
  age: 18,
  sex: '男'
}
let {name, ...attribute} = student
console.log(name, attribute); // 小凡 {age: 18, sex: '男'}

All variables are put into expansion variables;

 let student = {
    name: '小凡',
    age: 18,
    sex: '男',
    school: {
      name: '一中',
      location: '村里'
    }
  }
  let {name, school, ...attribute} = student
  console.log(name,school, attribute); // 小凡 {name: '一中', location: '村里'} {age: 18, sex: '男'}

array destructuring

Use [ ] for array deconstruction, and the variable name on the left is arbitrary;

let student = ['小凡', 18, '男'];
[name, age, sex] = student
console.log(name, age, sex); // 小凡 18 男

Others are the same as object deconstruction; 

Extended functions

Functions with parameter default values

ES6 adds parameter default values, so there is no need to write error-tolerant code inside the function;

// es5的写法
function add(a,b) {
  a = a || 10; // 若无定义a,则默认为10
  b = b || 20; // 若无定义b,则默认为20
  return a+b
}
console.log(add()); // 30

// es6的写法
function add(a = 10, b = 20) {
  return a + b
}
console.log(add()); // 30

The remaining parameters represent indeterminate parameters

The variable parameter function is the same as the arguments of es5;

// es5写法
function pick(obj) {
  let result = {};
  for(let i = 1; i < arguments.length; i++) {
    result[arguments[i]] = obj[arguments[i]]
  }
  return result;
}
let book = {
  name: '活着',
  author: '余华',
  pages: 400
}
let bookData = pick(book, 'name', 'author','pages');
console.log(bookData); // {"name": "活着", "author": "余华","pages": 400}
function pick(obj, ...keys) {
  let result = {};
  for(let i = 0; i < keys.length; i++) {
    result[keys[i]] = obj[keys[i]];
  }
  return result;
}
let book = {
  name: '活着',
  author: '余华',
  pages: 400
}
let bookData = pick(book, 'name', 'author','pages');
console.log(bookData); // {"name": "活着", "author": "余华","pages": 400}

arrow function

There are no arguments and no prototype attribute in the arrow function, and the arrow function is not an object, so the new keyword cannot be used to instantiate the arrow function;

It uses => to define, function() {} is equivalent to () => {}

The this of the arrow function points to the this of its parent object

extended object

Write variables and functions directly, as properties and methods of objects

// es6写法
const name = "活着";
const author = "余华";

const book = {
  name,
  author,
  sayName() {
    console.log('这是一本很好看的书籍');
  }
}
book.sayName() // 这是一本很好看的书

 The above abbreviation method name can only be abbreviated when the attribute and attribute value are the same ~

// es5写法
const name = "活着";
const author = "余华";

const book = {
  name: name,
  author: author,
  sayName: function() {
    console.log('这是一本很好看的书籍');
  }
}
book.sayName() // 这是一本很好看的书

新增Object.is()/Object.assign()/Object.keys/Object.value/Object.entries/Object.getOwnPropertyDescriptors方法

  • Object.is()

The Object.is() method is used to judge whether two values ​​are strictly equal, and returns a Boolean value; the difference from === is that the processing results for NaN and +0, -0 are different;

object1 = {
   name: '小明',
   age: 12
}
object2 = {
   name: '小明',
   age: 12
}
console.log(object2.name === object2.name); // true
console.log(Object.is(object1.name, object2.name)); // true
console.log(null === null); // true
console.log(Object.is(null, null)); // true
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(+0,-0)); // false
console.log(+0 === -0); // true
// 补充几个烦人的比较
console.log(null instanceof Object); // false,但null也是个对象
console.log(null === undefined); // false
console.log(null == undefined); // true
console.log(NaN == NaN); // false
console.log(undefined == undefined); // true
var x = new Boolean(false);
console.log(x); // Boolean {false} 
var y = Boolean(0);
console.log(y);  // false
  • Object.assign()

The Object.assign() method is used to merge all enumerable properties in multiple objects and return the target object; it is a shallow copy method~

object1 = {
    name: '小明',
    age: 12
}
object2 = {
    sex: 'male'
}
console.log(Object.assign(object1, object2)); // {name: '小明', age: 12, sex: 'male'}
  • Object.keys()

Object.keys() is used to return all properties in the object, returning an array

object1 = {
   name: '小明',
   age: 12
}
console.log(Object.keys(object1)); // ['name', 'age']
  • Object.values()

Object.values() is used to return all attribute values ​​in the object, returning an array

object1 = {
  name: '小明',
  age: 12
}
console.log(Object.values(object1)); // [['小明', 12]
  •  Object.entries()

Object.entries() is used to return multiple arrays, each array is composed of key-value

 object1 = {
   name: '小明',
   age: 12,
   classes: ['语文', '数学', '英语']
 }
 console.log(Object.entries(object1)); // [ "name","小明"],["age",12],["classes",["语文","数学","英语"] ] ]
  • Object.getOwnPropertyDescriptors

This method returns the description object of all the properties of the specified object;

<script>
  const obj = {
    name: 'xiaoming'
  }
  console.log(Object.getOwnPropertyDescriptors(obj)); 
</script>

For objects created by literals, the default enumerable property is true, the configurable property configurable (deletable and other properties) is true, and the writable property is true;

Supplement : Create an object through the Object.creat() method, and use the existing object as the prototype of the newly created object.

extended value

  • Number.EPSILON represents the minimum precision, generally used to judge whether the decimals are equal
  • Number.isFinite is used to check whether a value is a finite value
  • Number.isNaN is used to check whether a value is NaN
  • Number.parseInt is used to extract the integer part of the string Number.parseFloat is used to extract the floating point number in the string
  • Number.isInteger Determines whether a value is an integer
  • Math.trunc is used to erase the decimal part of the number
  • Math.sign is used to determine whether a number is positive/negative or 0. Positive numbers return 1, negative numbers return -1, and 0 returns 0.
console.log(0.1+0.2 === 0.3); // false
// 但是可以写个函数 判断如果0.1+0.2 与0.3相差小于Number.EPSILON,则表明0.1+0.2 与0.3相等
console.log(Number.isFinite(100)); // true
console.log(Number.isFinite(100/0)); // false
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(0)); // false
console.log(Number.parseInt('321flos3')); // 321
console.log(Number.parseInt('3.21flos3')); // 3
console.log(Number.parseFloat('3.21flos3')); // 3.21
console.log(Number.parseFloat('3.2.1flos3')); // 3.2
console.log(Number.isInteger(3.21)); // false
console.log(Number.isInteger('3')); // false
console.log(Number.isInteger(3)); // true
console.log(Math.trunc(3.45)); // 3
console.log(Math.sign(3.45)); // 1
console.log(Math.sign(-3.45)); // -1
console.log(Math.sign(0)); // 0

Symbol

A new basic data type symbol is added to represent a unique value. The features are as follows:

The value of symbol is unique and used to resolve naming conflicts;

Symbol values ​​cannot be operated with other data;

Create Symbol values ​​through Symbol() or Symbol.for();

The object properties defined by Symbol cannot be traversed using the for...in loop, but you can use Reflect.ownKeys to get all the key names of the object;

    <script>
        let s1 = Symbol();
        console.log(s1, typeof s1); // Symbol() 'symbol'
        // 带有标识的创建
        let name = Symbol('小明');
        console.log(name, typeof name); // Symbol(小明) 'symbol'
        // 使用Symbol.for创建
        let project = Symbol.for('英语');
        console.log(project, typeof project); // Symbol(英语) 'symbol'
    </script>

 Generally, when creating a unique property of an object, use Symbol

     <script>
        const project = Symbol()
        const number = Symbol()
        let school = {
            name: '一中',
            location: '这里',
            [project]: function() {
                console.log('我喜欢英语');
            },
            [number]: 200
        }
        school[project](); // 我喜欢英语
        console.log(school[number]); // 200
    </script>

Symbol is the sixth basic data type in JavaScript, juxtaposed with undefined, null, Number, String, and Boolean~

Maps and Sets

Set

ES6 provides a new data structure Set ( collection ), but the values ​​of the members are unique , and the collection implements the iterator interface, so you can use the extension operator and for...of... to traverse ;

The properties and methods of the Set object mainly include:

        size: Returns the number of elements in the collection (equivalent to the length attribute in the array);

        add: Add a new element and return the current collection;

        delete: delete the element and return a Boolean value;

        has: Check whether an element is contained in the collection and return a Boolean value;

 let newSet = new Set([1,3]);
 console.log(newSet); // Set(2) {1, 3}
 console.log(newSet.add([4,5])) // Set(3) {1, 3, [4, 5]}
 console.log(newSet.delete(3)) // true
 console.log(newSet.delete(4)) // false
 console.log(newSet.has(1)) // true
 console.log(newSet.size); // 2
  • Using the characteristics of the uniqueness of the Set object, the deduplication of the array can be realized~
  let newSet = [...new Set([1,3,3,5,4,4,6,7])];
  console.log(newSet); //  [1, 3, 5, 4, 6, 7]
  • Realize the intersection of arrays~
let arr1 = [1,2,3,4,5];
let arr2 = [1,4,6,7];
let arr3 = [...new Set(arr1)].filter(item => new Set(arr2).has(item))
console.log(arr3); //  [1, 4]
  • Realize the difference of array~
let arr1 = [1,2,3,4,5];
let arr2 = [1,4,6,7];
let arr3 = [...new Set(arr1)].filter(item => !(new Set(arr2).has(item)))
console.log(arr3); //  [2,3,5]
  • Realize the union of arrays~
 let arr1 = [1,2,3,4,5];
 let arr2 = [1,4,6,7];
 let arr3 = [...new Set([...arr1, ...arr2])]
 console.log(arr3); //  [1, 2, 3, 4, 5, 6, 7]

Map

ES6 provides the Map data structure, which is a collection of key-value pairs. The definition of keys is no longer limited to strings like objects, but includes various types of values ​​( including objects ). At the same time, because Map implements the iterator interface, it can be traversed using for...of;

The properties and methods of Map mainly include:

        size: returns the number of elements in the Map

        set: Add a new element and return the current Map;

        get: returns the key value of the key-value object;

        has: detects whether an element is contained in the current Map, and returns a Boolean value;

        clear: Clear the collection and return undefined

let newMap = new Map();
newMap.set('name', '小明');
newMap.set('classes', ['语文', '数学', '英语']);
console.log(newMap); //  Map(2) {'name' => '小明', 'classes' => Array(3)}
console.log(newMap.size); // 2
console.log(newMap.has('name')); // true
for (const item of newMap) {
   console.log(item); // (2) ['name', '小明'] (2) ['classes', Array(3)]
}
console.log(newMap.delete('classes')); // true
console.log(newMap.size); // 1
console.log(newMap.get('name')); // 小明

Iterators and generators/Proxy objects

Go back and talk in detail

Promise

Seeing 2023, are you still having a headache for Promise?_Confused Xiaoxiaotao's Blog-CSDN Blog

class class

The essence of a class is still a function

See Advanced JavaScript Tutorial (Object-Oriented Programming)

Modular implementation

Modularization is to split complex programs into individual files according to certain rules, and finally combine them together, which can reduce code complexity, avoid naming conflicts, and improve reusability;

The modular function in ES6 is mainly composed of two commands: export and import, the export command is used to expose the external interface of the module, and the import command is used to introduce the functions provided by other modules;

Exported modules can be exposed in three different ways :

  • Separate exposure methods

If the exported modules are exposed separately , such as:

// test.js文件
  // 通用暴露
export let name = '小明';
export function exam() {
  console.log('明天又要考试~');
}
  • uniform exposure

If the export module adopts a unified exposure method, such as:

// test.js文件
// 统一暴露
let name = '小明';
function exam() {
    console.log('明天又要考试~');
};
export {name, exam};

Note that {name, exam} here does not mean destructuring assignment, but just a way of writing~

Then when importing the module use:

<script type="module">
  // 通用暴露
  import * as m1 from './test.js'
  // 给*起了别名m1
  console.log(m1); // m1中包含name属性和exam方法
</script>
  • exposed by default

If the export module adopts the default exposure method, this method is generally applied to only one exposure in a file, such as:

// test.js文件
// 默认暴露
export default {
    name : '小明',
    exam: function() {
        console.log('明天又要考试~');
    }
};

Depending on the method of exposing the module, there are different ways to import the module :

  • General import method

This method can be used for the above three exposure methods:

<script>
  // 通用暴露
  import * as m1 from 'm1.js'
  // 给*起了别名m1
  console.log(m1); // 对于前两种暴露方式m1中包含name属性和exam方法,
  // 对于默认暴露方式,m1中包含default 取m1.default.name才可
</script>
  • Destructuring assignment

For the first two exposure methods, you can directly get the name or exam through the following code

<script type="module">
  // 通用暴露
  import { name,exam } from './test.js'
  // 或
  import { name as xingming,exam as kaoshi } from './test.js'
  // 给name/exam起了别名
</script>

But for the default exposure, use the following:

<script type="module">
   import { default as m1 } from './test.js'
   // 一般要给default取个别名,通过别名.name或别名.exam拿到
</script>
  • Simple import method for default exposure
<script type="module">
   import m3 from './test.js'
   // 通过m3.name或m3.exam拿到
</script>

The above three exposure methods can be introduced in another file at the same time without overwriting

Here, another important modular specification method CommonJs is simply added:

Modularized code in CommonJs mode can run on the server side, such as nodejs, or on the browser side (need to be compiled with the help of the tool Browserify). There are only two ways to expose it:

  • exports.xxx = value, value is the data to be exposed, xxx is the name
  • module.exports = value, value is the data to be exposed

The principle is that exports===module.exports={ } on the server side, both of them point to the same empty object;

These two methods cannot be mixed. If they are mixed, the one exposed by module.exports is the main one . What is the value, what is exposed by module.exports;

It shows that there is no attribute of englishName,

There are only two ways to introduce,

  • Introduce third-party modules, require(xxx), where xxx is the module name
  • Import custom modules, require(xxx), xxx is the module file path

Guess you like

Origin blog.csdn.net/ks795820/article/details/127750467