SoFunction
Updated on 2025-03-06

Summary of common tips for ES6 [deduplication, exchange, merge, inversion, iteration, calculation, etc.]

This article describes common tips for ES6. Share it for your reference, as follows:

1- Array deduplication

var arr = [1,2,3,4,3,4]; 
var arr2 = [...new Set(arr)];

At this time, arr2 is the array after deduplication~

2- Exchange the values ​​of two variables

let [x,y] = [1,2];
[y,x] = [x,y];
(y);

3- Get a character in a string

let arr= "hellomybo";
(arr[3]);

4-Use arrow functions instead of callback functions

How to write ES5

let a1 = [1,2,3].map(function (x) {
  return x * x;
});

ES6 arrow function writing

let a2 = [1,2,3].map(x => x * x);
(a1,a2);

5- Merge arrays

var arr1 = ['a', 'b'];
var arr2 = ['c'];
var arr3 = ['d', 'e'];

// Merge arrays for ES5(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]

// Merge arrays for ES6[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]

6- String inversion

let str = "12345678900987654321";

Original writing:

('').reverse().join('')

Expand writing method:

[...str].reverse().join('')

7- Filter the required values ​​and obtain the calculated values

filter:

['a',,'b'].filter(x => true)   // ['a','b']

calculate:

let arr = [1,2,3,4].map(x=>x+1);
(arr);

8-Array Dimension Reduction Use generator iterator

var arr = [1, [[2, 3], 4], [5, 6]];
var flat = function* (a) {
 var length = ;
 for (var i = 0; i < length; i++) {
  var item = a[i];
  if (typeof item !== 'number') {
   yield* flat(item);
  } else {
   yield item;
  }
 }
};
for (var f of flat(arr)) {
 (f);
}

Interested friends can use itOnline HTML/CSS/JavaScript code running toolhttp://tools./code/HtmlJsRunTest the above code running effect.

For more information about JavaScript, please view the topic of this site: "JavaScript object-oriented tutorial》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.