A brief summary of ES6

1. Introduction to ECMAScript

1. What is ECMA

The Chinese name of ECMA (European Computer Manufacturers Association) is the European Computer Manufacturers
Association. The goal of this organization is to evaluate, develop and approve telecommunications and computer standards. After 1994 the
organization changed its name to Ecma International

2. What is ECMAScript

ECMAScript is a scripting programming language standardized by Ecma International through ECMA-262.

3. What is ECMA-262

Ecma International has developed many standards, and ECMA-262 is just one of them. For a list of all standards, see
http://www.ecma-international.org/publications/standards/Standard.htm

4. Why learn ES6

  • The ES6 version has the most changes and is a milestone
  • ES6 adds many new grammatical features, making programming simpler and more efficient
  • ES6 is the front-end development trend, necessary skills for employment

2. New features of ECMAScript 6

1. let keyword

The let keyword is used to declare variables. Variables declared using let have several characteristics:

  1. Duplicate statement not allowed
let a = 1;
let a = 2;
var b = 3;
var b = 4;
a  // Identifier 'a' has already been declared
b  // 4

  1. block scope
       {
    
    
  let a = 0;
  var b = 1;
}
a  // ReferenceError: a is not defined
b  // 1
  1. variable hoisting does not exist
console.log(song);// ReferenceError: Cannot access 'song' before initialization
let song = '恋爱达人';
  1. does not affect the scope chain
 {
    
    
            let school = 'baicaotang';
            function fn(){
    
    
                console.log(school);
            }
            fn();//baicaotang
        }

Application scenario: It is right to use let to declare variables in the future

2. The const keyword

The const keyword is used to declare constants, const declarations have the following characteristics

  1. declaration must assign an initial value
const a;// SyntaxError: Missing initializer in const declaration
  1. Identifiers are generally uppercase
const PI = "3.1415926";
  1. Duplicate statement not allowed
const a=1;
const a=2;
//SyntaxError: Identifier 'a' has already been declared
  1. Value does not allow modification
const SCHOOL = 'baicaotang';
SCHOOL = 'ATGUIGU';
//TypeError: Assignment to constant variable.
  1. block scope
{
    
    
            const PLAYER = 'UZI';
        }
        console.log(PLAYER);
        //ReferenceError: PLAYER is not defined

Note: The modification of object properties and the change of array elements will not trigger const error application scenarios: declare object types using const, and select let for non-object type declarations

3. Variable deconstruction assignment

ES6 allows to extract values ​​from arrays and objects and assign values ​​to variables according to a certain pattern, which is called
destructuring assignment.

1. Array destructuring assignment

let [a, [[b], c]] = [1, [[2], 3]];
// a = 1
// b = 2
// c = 3

2. Object structure assignment

let {
    
    a = 10, b = 5} = {
    
    a: 3};
// a = 3; b = 5;
let {
    
    a: aa = 10, b: bb = 5} = {
    
    a: 3};
// aa = 3; bb = 5;

Note: If you frequently use object methods and array elements, you can use the destructuring assignment form

4. String

1. Identification of extended method strings

ES6 used the indexOf method to determine whether a string contains substrings. ES6 added a substring identification method.

  • includes(): Returns a Boolean value to determine whether the parameter string is found.
  • startsWith(): Returns a Boolean value to determine whether the parameter string is at the head of the original string.
  • endsWith(): Returns a Boolean value to determine whether the parameter string is at the end of the original string.

The above three methods can accept two parameters, the string to be searched, and an optional search starting position index.

let string = "apple,banana,orange";
string.includes("banana");     // true
string.startsWith("apple");    // true
string.endsWith("apple");      // false
string.startsWith("banana",6)  // true

2. String repetition

repeat(): Returns a new string, indicating that the string is repeated for the specified number of times.

console.log("Hello,".repeat(2));  // "Hello,Hello,"

3. String completion

  • padStart: returns a new string, indicating that the original string is completed from the head (left side) with the parameter string.
  • padEnd: returns a new string, indicating that the original string is completed from the end (right side) with the parameter string.

The above two methods accept two parameters, the first parameter specifies the minimum length of the generated string, and the second parameter is the string used for completion. If the second parameter is not specified, it will be filled with blanks by default.

console.log("h".padStart(5,"o"));  // "ooooh"
console.log("h".padEnd(5,"o"));    // "hoooo"
console.log("h".padStart(5));      // "    h"

4. Template strings

The template string (template string) is an enhanced version of the string, identified by backticks (`), features:

  1. Newline characters can appear in the string
let str = `<ul>
                    <li>沈腾</li>
                    <li>玛丽</li>
                    <li>魏翔</li>
                    <li>艾伦</li>
                    </ul>`;
  1. Variables can be output in the form of ${xxx}
 let lovest = '魏翔';
        let out = `${
      
      lovest}是我心目中最搞笑的演员!!`;
        console.log(out);

Note: Use template strings when strings and variables are concatenated

5. Label template

A tagged template is a function call where the argument to the call is a template string.

alert`Hello world!`;
// 等价于
alert('Hello world!');

5.Symbol

ES6 introduces a new primitive data type Symbol, which represents a unique value. The biggest usage is to define the unique property name of an object.

In addition to Number, String, Boolean, Object, null and undefined, ES6 data types also add Symbol.
Symbol Features

  1. The value of Symbol is unique to resolve naming conflicts
  2. Symbol values ​​cannot be manipulated with other data
  3. 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
//创建 Symbol
let s1 = Symbol();
console.log(s1, typeof s1);
//添加标识的 Symbol
let s2 = Symbol('baicaotang');
let s2_2 = Symbol('baicaotang');
console.log(s2 === s2_2);
//使用 Symbol for 定义
let s3 = Symbol.for('baicaotang');
let s3_2 = Symbol.for('baicaotang');
console.log(s3 === s3_2);
let sy = Symbol("key1");
//作为属性名 
// 写法1
let syObject = {
    
    };
syObject[sy] = "kk";
console.log(syObject);    // {Symbol(key1): "kk"}
 
// 写法2
let syObject = {
    
    
  [sy]: "kk"
};
console.log(syObject);    // {Symbol(key1): "kk"}
 
// 写法3
let syObject = {
    
    };
Object.defineProperty(syObject, sy, {
    
    value: "kk"});
console.log(syObject);   // {Symbol(key1): "kk"}

Note: When encountering a unique scenario, Symbol should be considered. When the Symbol value is used as a property name, the property is a public property rather than a private property, and can be accessed outside the class. But it will not appear in for…in, for…of loops, nor will it be returned by Object.keys(), Object.getOwnPropertyNames(). If you want to read the Symbol property of an object, you can get it through Object.getOwnPropertySymbols() and Reflect.ownKeys().

Symbol built-in value

In addition to defining the Symbol value used by itself, ES6 also provides 11 built-in Symbol values, which point to the methods used internally by the language. These methods can be called magic methods, because they will be executed automatically in certain scenarios.

reference documents

6.Map and Set

1.Set

ES6 provides a new data structure Set (collection). It is similar to an array, but the values ​​of its members are all unique
. The collection implements the iterator interface, so it can be traversed using the "extension operator" and "for...of...". The
properties and methods of the collection:

  1. size returns the number of elements in the collection
  2. add adds a new element and returns the current collection
  3. delete deletes an element and returns a boolean value
  4. has checks whether the collection contains an element and returns a boolean value
  5. clear clears the collection and returns undefined
//创建一个空集合
let s = new Set();
//创建一个非空集合
let s1 = new Set([1,2,3,1,2,3]);
//集合属性与方法
//返回集合的元素个数
console.log(s1.size);
//添加新元素
console.log(s1.add(4));
//删除元素
console.log(s1.delete(1));
//检测是否存在某个值
console.log(s1.has(2));
//清空集合
console.log(s1.clear());

2.Map

ES6 provides the Map data structure. It is similar to an object and is also a collection of key-value pairs. But the scope of "key"
is not limited to strings, and various types of values ​​(including objects) can be used as keys. Map also implements
the iterator interface, so it can be traversed using "spread operator" and "for...of...".
Properties and methods of Map :

  1. size returns the number of elements in the Map
  2. set adds a new element and returns the current Map
  3. get returns the key value of the key object
  4. has detects whether an element is contained in the Map and returns a boolean value
  5. clear clears the collection and returns undefined
//创建一个空 map
let m = new Map();
//创建一个非空 map
let m2 = new Map([
 ['name','baicaotang'],
 ['slogon','不断提高']
]);
//属性和方法
//获取映射元素的个数
console.log(m2.size);
//添加映射值
console.log(m2.set('age', 6));
//获取映射值
console.log(m2.get('age'));
//检测是否有该映射
console.log(m2.has('age'));
//清除
console.log(m2.clear());

7. Numerical expansion

1. Binary and Octal

ES6 provides a new way of writing binary and octal values, which are represented by prefixes 0b and 0o respectively.

//二进制
console.log(0b11 === 3); // true
console.log(0B11 === 3); // true
//八进制
console.log(0o11 === 9); // true
console.log(0O11 === 9); // true

2. Number.isFinite() 与 Number.isNaN()

Number.isFinite() is used to check whether a value is finite

console.log( Number.isFinite(1));   // true
console.log( Number.isFinite(0.1)); // true
// NaN 不是有限的
console.log( Number.isFinite(NaN)); // false
 
console.log( Number.isFinite(Infinity));  // false
console.log( Number.isFinite(-Infinity)); // false
 
// Number.isFinate 没有隐式的 Number() 类型转换,所有非数值都返回 false
console.log( Number.isFinite('foo')); // false
console.log( Number.isFinite('15'));  // false
console.log( Number.isFinite(true));  // false
 

Number.isNaN() is used to check if a value is NaN

console.log(Number.isNaN(NaN));      // true
console.log(Number.isNaN('true'/0)); // true
 
// 在全局的 isNaN() 中,以下皆返回 true,因为在判断前会将非数值向数值转换
// 而 Number.isNaN() 不存在隐式的 Number() 类型转换,非 NaN 全部返回 false
Number.isNaN("NaN");      // false
Number.isNaN(undefined);  // false
Number.isNaN({
    
    });         // false
Number.isNaN("true");     // false

3. Number.parseInt() and Number.parseFloat()

ES6 transplants the global methods parseInt and parseFloat to the Number object, and uses them unchanged.

// 不指定进制时默认为 10 进制
Number.parseInt('12.34'); // 12
Number.parseInt(12.34);   // 12
 
// 指定进制
Number.parseInt('0011',2); // 3
 
// 与全局的 parseInt() 函数是同一个函数
Number.parseInt === parseInt; // true
Number.parseFloat()
用于把一个字符串解析成浮点数。
Number.parseFloat('123.45')    // 123.45
Number.parseFloat('123.45abc') // 123.45
 
// 无法被解析成浮点数,则返回 NaN
Number.parseFloat('abc') // NaN
 
// 与全局的 parseFloat() 方法是同一个方法
Number.parseFloat === parseFloat // true

4. Math.trunc

Used to remove the fractional part of a number and return the integer part.

Math.trunc(12.3); // 12
Math.trunc(12);   // 12
 
// 整数部分为 0 时也会判断符号
Math.trunc(-0.5); // -0
Math.trunc(0.5);  // 0
 
// Math.trunc 会将非数值转为数值再进行处理
Math.trunc("12.3"); // 12
 
// 空值或无法转化为数值时时返回 NaN
Math.trunc();           // NaN
Math.trunc(NaN);        // NaN
Math.trunc("hhh");      // NaN
Math.trunc("123.2hhh"); // NaN

5. Number.isInteger

Number.isInteger() is used to determine whether a value is an integer

Number.isInteger(value)
Number.isInteger(0); // true
// JavaScript 内部,整数和浮点数采用的是同样的储存方法,因此 1 与 1.0 被视为相同的值
Number.isInteger(1);   // true
Number.isInteger(1.0); // true
 
Number.isInteger(1.1);     // false
Number.isInteger(Math.PI); // false
 
// NaN 和正负 Infinity 不是整数
Number.isInteger(NaN);       // false
Number.isInteger(Infinity);  // false
Number.isInteger(-Infinity); // false
 
Number.isInteger("10");  // false
Number.isInteger(true);  // false
Number.isInteger(false); // false
Number.isInteger([1]);   // false
 
// 数值的精度超过 53 个二进制位时,由于第 54 位及后面的位被丢弃,会产生误判
Number.isInteger(1.0000000000000001) // true
 
// 一个数值的绝对值小于 Number.MIN_VALUE(5E-324),即小于 JavaScript 能够分辨
// 的最小值,会被自动转为 0,也会产生误判
Number.isInteger(5E-324); // false
Number.isInteger(5E-325); // true
Number.isSafeInteger()
//用于判断数值是否在安全范围内。
Number.isSafeInteger(Number.MIN_SAFE_INTEGER - 1); // false
Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1); // false

Reference Documents: Rookie Tutorial
Reference Books: Ruan Yifeng Tutorial

Guess you like

Origin blog.csdn.net/morensheng/article/details/120937772