Shang Silicon Valley ES6 review summary (65th)

1. Set (collection)

1.1. Definition and use of Set

ES6 provides new data structures Set(collections). It is similar to an array, but the values ​​​​of the members are unique , and the collection implements iteratorthe interface , so it can for...ofbe traversed using the spread operator and .

The attributes and methods of collections (assuming a collection st here)

1. st.size: Return the number of collections
2. st.add(item): Add a new element to the collection itemand return the current collection
3. st.delete(item): Delete elements in the collection and return booleana value
4. st.has(item): Check whether the collection contains an element and return booleana value
5. st.clear(): Clear Collection
6. The collection is converted into an array: [...st]
7. Merge two collections:[...st1, ...st2]

example

//创建一个非空集合
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());

1.2. Collection case

Case 1: Array deduplication

let arr1 = [1, 2, 2, 3, 3, 3, 4, 1, 2];
let res1 = [...new Set(arr1)];  // 扩展运算符将集合转变为数组
console.log(res1); // [ 1, 2, 3, 4 ]

Case 2: Array Intersection

let arr1 = [1, 2, 2, 3, 4, 5];
let arr2 = [3, 6, 6, 7, 1, 4];
let res = arr1.filter(v => new Set(arr2).has(v))
console.log(res); // [ 1, 3, 4 ]

Case 3: Array union

let arr1 = [1, 2, 2, 3, 4, 5];
let arr2 = [3, 6, 6, 7, 1, 4];
let res = [...new Set([...arr1, ...arr2])];  // 都合起来再去重
console.log(res); // [ 1, 2, 3, 4, 5, 6, 7 ]

Case 4: Array difference set (a difference set of 1 and 2 is what is in 1 but not in 2, this stuff is divided into subjects)

let arr1 = [1, 2, 2, 3, 4, 5];
let arr2 = [3, 6, 6, 7, 1, 4];
let res = [...new Set(arr1)].filter(v => !(new Set(arr2).has(v)))  // 交集的逆运算,非一下里面的运算就行了
console.log(res); // [ 2, 5 ]

2、Map

ES6 provides Mapdata structures. 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. MapAlso implements iteratorthe interface , so it can for...ofbe traversed using the spread operator and .
Define a Map:

let mp1 = new Map();
mp1.set('aaa', 111);
mp1.set('bbb', 222);
mp1.set('ccc', 333);

let mp2 = new Map([
    ['aaa', 111],
    ['bbb', 222],
    ['ccc', 333]
]);

console.log(mp1['aaa']); // 111
console.log(mp2.get('bbb')); // 222

Map properties and methods: (k is the key, v is the value)

size:返回 Map 的元素(键值对)个数
set(k, v):增加一个键值对,返回当前 Map
get(k):返回键值对的键值
has():检测 Map 中是否包含某个元素
clear():清空集合,返回 undefined

3. Value expansion

1. Number.EPSILONIt is the minimum precision JavaScriptrepresented by and is generally used to handle floating-point arithmetic. For example, it can be used to compare two floating point numbers.

let equal = (x, y) => Math.abs(x - y) < Number.EPSILON;
console.log(0.1 + 0.2 === 0.3); // false
console.log(equal(0.1 + 0.2, 0.3)); // true

2. Binary and octal: binary starts with 0b, octal starts with 0o.

let b = 0b1010;
let o = 0o777;
let d = 100;
let x = 0xff;
console.log(x);

3. Number.isFiniteCheck whether a value is a finite number.

console.log(Number.isFinite(100)); // true
console.log(Number.isFinite(100 / 0)); // false
console.log(Number.isFinite(Infinity)); // false

4, Number.parseIntand Number.parseFloat
ES6 Numberadded parseIntthe method, Number.parseIntwhich is exactly equivalent to parseInt. Convert a string to an integer, or perform a base conversion. Number.parseFloatis equivalent toparseFloat

Number.parseInt === parseInt; // true
Number.parseFloat === parseFloat; // true
console.log(Number.parseInt('5211314love')); // 5211314
console.log(Number.parseFloat('3.1415926神奇')); // 3.1415926

5. Number.isInteger()Determine whether a number is an integer.

console.log(Number.isInteger(5)); // true
console.log(Number.isInteger(2.5)); // false

6. Math.trunc()Erase the decimal part of the number.

console.log(Math.trunc(3.5)); // 3

7. Math.signDetermine whether a number is positive, negative or zero

4. Object method extension

ES6 adds some new Objectobject methods.

1. Object.isCompare whether the two values ​​are strictly equal, which is ===basically consistent with the behavior.
2. Object.assignWhen merging objects, copy all enumerable properties of the source object to the target object.
3. __proto__, setPrototypeOf, setPrototypeOfyou can directly set the prototype of the object

4.1 Object.is()

Object.is()method to determine whether two values ​​are exactly the same. Object.isCompares whether two values ​​are strictly equal, roughly the same ===behavior as . Returns a Booleantype .

Object.is(value1, value2);

Object.is()method to determine whether two values ​​are the same value. Two values ​​are equal if:

1. Both are undefined
2, both are null
3, both are trueor false
4, all are strings of the same length and the same characters are arranged in the same order
5, all are the same object (meaning that each object has the same reference)
6, both Numbers and
1, all +0
2, all -0
3, all NaN
4, or both non-zero and non-NaN and the same value

1. It is different from ==the operation . ==The operator coerces the variables on both sides (if they are not of the same type) before evaluating equality
(the result of this behavior will be "" == falseevaluated as true), Object.iswithout coercing the values ​​on both sides.

2. It is ===also a little different from . ===operators (also the == operator) treat the numbers -0 and +0 as equal, and treat Number.NaNand NaNunequal

4.2 Object.assign(merge object)

Object.assignThe merging of objects is equivalent to a shallow copy.

const config1 = {
    
    
    host: 'localhost',
    port: 3306,
    name: 'root',
    pass: 'root',
    test: 'test'
};
const config2 = {
    
    
    host: 'http://atguigu.com',
    port: 33060,
    name: 'atguigu.com',
    pass: 'iloveyou',
    test2: 'test2'
}
console.log(Object.assign(config1, config2));

4.3 Object.setPrototypeOf 和 Object.getPrototypeof

Object.setPrototypeOfThe prototype object used to set the object, Object.getPrototypeofthe prototype object used to get the object, equivalent __proto__.

const school = {
    
    
    name: '尚硅谷'
}
const cities = {
    
    
    xiaoqu: ['北京','上海','深圳']
}
Object.setPrototypeOf(school, cities);
console.log(Object.getPrototypeOf(school));
console.log(school);

5. ES6 Modularity

Modularization refers to splitting a large program file into many small files, and then combining the small files.

The benefits of modularity

The advantages of modularity are as follows:

1. Prevent naming conflicts
2. Code reuse
3. High maintenance

Modular Specification Products

Modular specifications prior to ES6 are:

1、CommonJS => NodeJS、Browserify
2、AMD => requireJS
3、CMD => seaJS

ES6 modular syntax

The module function mainly consists of two commands: exportand import.

1. exportThe command is used to specify the external interface of the module
2. importThe command is used to input the functions provided by other modules

1. Expose separately

// 单个导出
export let uname = 'Rick';
export let sayHello = function () {
    
    
    console.log('Hi, bro!');
}

2. Uniform exposure

let uname = 'Rick';
let sayHello = function () {
    
    
    console.log('Hi, bro!');
}
// 合并导出
export {
    
     uname, sayHello };

3. Default exposure

// 默认暴露
export default {
    
    
    uname: 'Rick',
    sayHello: function () {
    
    
        console.log('Hi, bro!');
    }
}

4. Module import

1. General import method

import * as m1 from './js/m1.js';
import * as m2 from './js/m2.js';
import * as m3 from './js/m3.js';

2. Deconstruction assignment form import

import {
    
     uname, sayHello } from './js/m1.js';
// 有重复名可以设置别名
import {
    
     uname as uname2, sayHello as sayHello2 } from './js/m2.js';
console.log(uname);
// 配合默认导出
import {
    
    default as m3} from "./src/js/m3.js";

3. Import in a simple way, for default exposure

import m3 from "./src/js/m3.js";  // 用导入的模块名称作为函数名

5. ES6 uses modularization 2

Write the file imports into an app.js file, and then write the modules to be imported in it. The content in app.js is as follows:

import * as m1 from './js/m1.js';
import * as m2 from './js/m2.js';
import * as m3 from './js/m3.js';

console.log(m1);
console.log(m2);
console.log(m3);

index.htmlInclude the contents of the file in app.js:

<script src="./app.js" type="module"></script>

6. Use babel to convert modular code

Some browsers do not support ES6 syntax, so you need to use babel to convert it into ES5 equivalent syntax.

1. Installation tools

npm i babel-cli babel-preset-env browserify(webpack) -D

2. Compile

npx babel src/js -d dist/js --presets=babel-preset-env

3. Packing

npx browserify dist/js/app.js -o dist/bundle.js

7. ES6 modularization introduces npm installed packages

npm install jquery

Then importimport it .

Guess you like

Origin blog.csdn.net/weixin_55608297/article/details/128106321