ES6 javascript practical development skills

ES6 Practical Development Tips

Define variables/constants

In ES6, letand consttwo new commands have been added, which letare used to define variables and constdefine constants. The difference between the two commands and the original varcommands is that they let, constare both block-level scopes, and their effective scope is only in the code block. as follows:

//es5
if(1==1){
  var b = 'foo';
}
console.log(b);//foo

//es6
if(1==1){
  let b = 'foo';
}
console.log(b);//undefined

define constant object

const a = {a:1,b:2};
a.b = 3;
console.log(a);//{a:1,b:3}

In the above example, after the content of the constant a is defined, it is still valid to modify it. The reason is that the use of the object type is a pointer reference. The constant is just a pointer to the object, but the content of the object itself can still be modified. Note , arrays ( Array) are also objects; then if you define constants using underlying data types: string, number, booleanetc.

const a = 1;
a = 2;// Uncaught TypeError: Assignment to constant variable.

In use, it is recommended to use letwith and constcompletely instead of the varcommand

Numerical expansion

convert Number.parseInt - convert string or number to integer Number.parseFloat- convert string or number to float

Number.parseInt, Number.parseFloatand parseInt, parseFloathave the same function. In ES6, it is recommended to use Number.the method to call. The purpose of this is to reduce the use of the code as much as possible with global methods, and the language used is gradually modularized.

test function

//测试是否整数
Number.isInteger(21)//true
Number.isInteger(1.11)//false

//测试是否NaN
Number.isNaN(Nan)//true
Number.isNaN(1)//false

<br><br>

string expansion

String content test

'abcdef'.includes('c');//true
'abcdef'.includes('ye');//false
'abcdef'.startsWith('a');//true
'abcdef'.endsWitch('f');//true

//includes(), startsWith(), endsWith() 都支持第二个参数,
//类型为数字类型,意为从第 n 个字符开始,endsWith()的第二个参数有点不一样
'abcdef'.includes('c', 4);//false 从第5个字符开始查找是否有 'c' 这个字符
'abcdef'.startsWith('d', 3);//true 从第4个字符开始查找是否是以 'd' 字符为开头
'abcdef'.endsWith('d', 4);//true 前面的4个字符里,是否以 'd' 字符为结尾

Repeated output of string content

'a'.repeat(5);//aaaaa 重复输出5遍

Native support for template languages

//es5
$('#result').append(
  'There are <b>' + basket.count + '</b> ' +
  'items in your basket, ' +
  '<em>' + basket.onSale +
  '</em> are on sale!'
);
//es6
//在es6中,内容模板,可以定义在 `` 包起来的字符串中,其中的内容会保持原有格式
//另外可以在字符串中直接使用模板语言进行变量填充,优雅而简洁
$('#result').append(`
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!
`);

String traversal output

//for ...of 格式为 es6 中的 Iterator 迭代器的输出方式
for(let c of 'abc'){
  console.log(c);
}
//a
//b
//c

string completion

//参数1:[number] 目标字符串长度
//参数2:[string] 进行补全的字符串
'12345'.padStart(7, '0')//0012345 - 字符串不足7位,在头部补充不足长度的目标字符串
'12345'.padEnd(7, '0')//1234500 - 在尾部进行字符串补全

array expansion

Merge arrays

let a = [1, 2];
let b = [3];
let c = [2, 4];
let d = [...a, ...b, ...c];//[1, 2, 3, 2, 4] 所有内容合并,但并不会去除重复

fast conversion to array

Array.of(3,4,5)//[3,4,5]

array content test

//判断对象是否为数组
if(Array.isArray(obj)){...}

[1,2,3].includes(5);//false,检索数据中是否有5

//找出第一个匹配表达式的结果,注意是只要匹配到一项,函数即会返回
let a = [1, 3, -4, 10].find(function(value, index, arr){
  return value < 0;
});
console.log(a);//-4

//找出第一个匹配表达式的结果下标
let a = [1, 3, -4, 10].findIndex(function(value, index, arr){
  return value < 0;
});
console.log(a);//2

Content filtering

//排除负数内容
let a = [1, 3, -4, 10].filter(function(item){
  return item > 0;
});
console.log(a);//[1, 3, 10]

Content instance

.keys()- Get the key name of all elements in the array (actually the subscript index number)

.values()- get the data of all elements in the array

.entries()- Get the key name and data of all data in the array

for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

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

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"

.entries(), .keys(), the function.values() is similar to several functions of the same name in , and it is not very practical in actual use. For the operation of the array, you can directly traverse it.Object

object extension

Concise representation of properties

//直接使用变量/常量的名称个为对象属性的名称
let a = 'abc';
let b = {a};//{a: 'abc'}

function f(x, y){ return {x, y};}
//等效于
function f(x, y){ return {x: x, y: y}}

let o = {
  f(){ return 1; }
}
//等效于
let o = {
  f: function(){ return 1; }
}

Determine if an object is an array

if(Object.isArray(someobj)){}

object content merging

let a = {a:1,b:2}, b = {b:3}, c = {b:4,c:5};
let d = Object.assign(a, b, c);
console.log(d);//{a:1,b:4,c:5}
console.log(a);//{a:1,b:4}
//上面的合并方式会同时更新 a 对象的内容,a 的属性如果有多次合并会被更新数据,
//但自身没有的属性,其它对象有的属性不会被添加到 a 身上;
//参数列中的对象只会影响第一个,后面的参数对象不会被修改数据

//推荐使用这种方式进行对象数据合并
let a = {a:1,b:2}, b = {b:3}, c = {b:4,c:5};
let d = Object.assign({}, a, b, c);//第一个参数增加一个空对象,在合并时让它被更新,不影响实际的对象变量内容
console.log(d);//{a:1,b:4,c:5}//与上面的方式合并结果一致,使用这种方式, a 对象的内容就不会被影响了

The direction of object content merging is from the back of the parameter order to the front

Object Content Collection

Object.keys()- Get all the key names in the object, return it as an array

var obj = { a:1,b:2 };
var names = Object.keys(obj);//['a', 'b']

Object.values()- Get all the value content in the object and return it in the form of an array

var obj = { a:1,b:2 };
var values = Object.values(obj);//[1, 2]

Object.entries()- Get all member data in the object and return it in the form of an array, and the content of the members is also in the form of an array

var obj = { a:1,b:2 };
var values = Object.entries(obj);//[['a',1], ['b',2]]

In fact, it can be observed that , Object.keys(), Object.values(), areObject.entries() consistent with the methods in , whether it is the method name or the specific usage, which can also help to understand these functional APIsJavaMAP

destructuring assignment

let [a, b, c] = [1, 2, 3];
//定义了三个变量,并对应赋了值;如果值的个数与变量名个数不匹配,没有对应上的变量值为 undefined

let [a, b, c='default'] = [1, 2];
//指定默认值,在定义变量时就指定了默认值,如果赋值时,没有给定内容,则会取默认值

let [a, …b] = [1,2,3];
//这里 b 的值为[2,3],这样可以快速使用剩余的数据赋值给变量,
//但实际使用中为了避免代码阅读的歧义,不推荐这么使用,仅作了解即可

let [a,b,c] = 'yes';
console.log(a);//y
console.log(b);//e
console.log(c);//s
字符串的解构赋值会以单个字符的方式进行赋值

let {length}='yes';
console.log(length);//3
以对象赋值的方式,如果名称是字符串的自带属性,则会获得属性值

let arr = [1,2];
let obj = {a:1,b:2};
function test ({a = 10, b}){
	console.log('a:',a);
	console.log('b:',b);
}
test(obj);
解构赋值的使用实例,作为函数传参,并使用默认值

object structure destructuring

let obj = {a: 1, b: 2};
let {a, b} = obj;//a=1,b=2
使用变量的方式进行结构赋值,需要严格匹配名称,数组的模式是严格匹配下标

let obj = {a: 1, b: 2};
let {a=0, b=5} = obj;
赋值并给定默认值

let obj = {a: 1, b: 2};
let {a:A, b} = obj;//A=1,b=2,a报错,变量未定义
获得内容后,将变量进行改名

let obj = {a: 1, b: 2};
let a = 0;
({a, b} = obj);
对已存在的 a 进行修改值,并生成新的变量 b

let obj = {
	arr: ['aaa',{a:1}]
};
let {arr:[b, {a}]} = obj;//这里的arr互相映射
console.log(b);
console.log(a);
获得对象的子数据,并映射到相应的变量,这里需要注意的是结构要对应

modular

The use case of the simplest example

//a.js
let a = {a:1,b:2,c:3};
export default a;

//b.js
import a from 'a.js';//假设 a.js 与 b.js 同在一个目录中
console.log(a.a);//1

The above simple example illustrates two script files in actual use, which can refer to each other and obtain the data in the target file; we can think that one script file is one 模块, then in the actual development process, we can use Business processing content, or data processing process 抽象In a file, when it needs to be used, the data imported and used by other modules

Full content: https://github.com/TerryZ/js-develop-skill-summary

Personal original content, reprint please indicate the source

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324520031&siteId=291194637