Although ES6 has been released for a long time, there are still not many people using it in my work, especially front-end development with little work experience, or some back-end development that requires both front-end and back-end development. I even see some ES6 writing methods, but I don’t know what it means. Here I introduce some common ES6 writing methods:
1. Common value methods
This method makes it easy to take multiple values from an object
1.
const obj = {
name: 'wang'.age:20,}const {name, age} = obj || [];
const param = {
array: [1.2.3.4].obj: {a:1.a1:2}}const{array, obj} = obj || []; orconst {a:name} = obj;
console.log(a1);/ / wang
2.
const param = {
array: [1.2.3.4].obj: {a:1.a1:2}}const{array, obj} = obj || []; orconst {a:array} = obj;
console.log(array);/ / [1, 2, 3, 4]
Copy the code
2. Merge data
We often merge arrays or objects to display or pass in interfaces (shallow copy)
const arr1 = ['a1'.'a2'.'a3']; const arr2 = ['b1'.'a1'.'b2']; const c = [...new Set([...arr1,...arr2])];//['a1','a2','a3','b1','b2']
const obj1 = { a:1,}const obj2 = { b:1,}constobj = {... obj1,... obj2};//{a:1,b:1}
Copy the code
3. Concatenate strings
const date = '2021-10-01';
const score = 90;
const result = `${date}${score > 90?'good':'come on! '}`;
Copy the code
4. Query the array
Usually when we’re doing data matching we’re going to be matching objects in an array and getting some data by keyword
const data = [{id: 1.name: 'wang'.age: 20}, {id: 2.name: 'wang'.age: 18}, {id: 3.name: 'wang'.age: 18}];
const result = data.find(
item= >{
return item.id === 1})console.log(result) // {id: 1, id: 1, age: 20}
Copy the code
5. IF judgment
Judge for multiple conditions
const condition = [1.2.3.4];
if( condition.includes(type) ){
/ /...
}
Copy the code
6. It involves the judgment of being empty or undefined
if(value??' '! = =' ') {/ /...
}
Copy the code