Collected 22 practical JavaScript tips, you must be able to use

1. Array de duplication

const arr = [1, 2, 2, 3, 4, 5, 5, 3]
//Mode 1:
const newArr1 = [...new Set(arr)]
//Mode 2
const newArr2 = arr.reduce((prev,cur) => prev.includes(cur) ? prev : [...prev,cur],[]);
console.log(newArr1) //[1, 2, 3, 4, 5]
console.log(newArr2) //[1, 2, 3, 4, 5]

2. Generate an array of [1-100]

// Mode 1
const arr1 = [...Array(100).keys()] 
// Mode 2
const arr2 = Array.from(Array(100), (e, i) => i + 1)

3. Gets the last element in the array

var array = [1,2,3,4,5,6];
console.log(array.slice(-1)); // [6]
console.log(array.slice(-2)); // [5,6]
console.log(array.slice(-3)); // [4,5,6]

tip: the slice(begin,end) method is used to get the array elements between begin and end. If you do not set the end parameter, the default length of the array will be taken as the end value. But some students may not know that this function can also accept negative values as parameters. If you set a negative value as the value of begin, you can get the last element of the array

4. Array truncation

var array = [1,2,3,4,5,6];
console.log(array.length); // 6
array.length = 3;
console.log(array.length); // 3
console.log(array); // [1,2,3]

tip: this trick is mainly used to lock the size of the array. It is very useful for deleting some elements in the array. For example, if your array has 10 elements, but you only want the first five elements, you can truncate the array by array.length=5

5. Merge array

var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.concat(array2)); // [1,2,3,4,5,6];

6. Delete the last two elements of the array

    let a = [1, 2, 4, 5];
    a.length = a.length - 2;
    console.log(a.length); // 2

7. Shuffle of array elements

var list = [1,2,3];
console.log(list.sort(function() { Math.random() - 0.5 })); // [2,1,3]

8. Multidimensional array flattening

const arr = [1, 2, 3, [4, [5, 6, [7,8]]]];
// Mode 1:
console.log(arr.flat(Infinity));  //[1, 2, 3, 4, 5, 6, 7, 8]
// Mode 2:
console.log(arr.join().split(','));  //['1', '2', '3', '4', '5', '6', '7', '8']
// Mode 3:
console.log(arr.toString().split(','));  //['1', '2', '3', '4', '5', '6', '7', '8']
// In consulting the data, bloggers found that the original join() and toString() functions can span levels, so they have methods 2 and 3

9. Find the intersection and difference of two arrays

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
let intersect = new Set([...a].filter(x => b.has(x))); // intersection
let difference = new Set([...a].filter(x => !b.has(x)));  // Difference set

10. Gets the maximum and minimum values of the array

let numbers = [1, 3, 5, 5, 6, -3, 10]
let max = Math.max(...numbers)  //Maximum
let min = Math.min(...numbers)   //minimum value
console.log(max); // 10
console.log(min); //-3

11. String inversion

 let str = "hello world";
 console.log([...str].reverse().join(""));  // dlrow olleh

12. Counts the number of occurrences of the same character in the string

let str = 'aaabbbccddeegggggggllllssgjwd';
let strInfo = str.split('').reduce((p, c) => (p[c]++ || (p[c] = 1), p), {});
console.log(strInfo)  //{a: 3, b: 3, c: 2, d: 3, e: 2, g: 8, j: 1, l: 4, s: 2, w: 1}

13. Use the operator "|" to set the default value

let a = 111
let b = a || 'default value'
// If a has a value, the value of a is displayed. If there is no value, the default value is displayed

13. Better '?' than '?' operator

let a = a ?? 'default value'
// Unlike the logical or operator (|), the logical or operator returns the right operand when the left operand is false.
That is, if you use || To set default values for some variables, you may encounter unexpected behavior. For example, false (for example,'' Or 0).

14. Implicit escape (string to number)

let a = '1';
console.log(Number(a)); // 1
console.log(+a);  //1
// Using implicit escape can be simpler and faster

15. Implicit escape (string to number) numeric amount thousands formatting

let a = 123456789;
console.log(a.toLocaleString('en-US')) //123,456,789

16. Bitwise operator

Math.floor(5.9) === 5  //true
 After abbreviation
~~5.9 === 5  //true
// You can use a bitwise operator instead of Math.floor(). The advantage of the double no positioning operator is that it performs the same operation faster.

17. Decimal rounding

let num = 123.456

// common method
console.log(parseInt(num)); // 123
// Bitwise OR
console.log(num | 0); // 123
// Bitwise non operator
console.log(~~ num); // 123
// Shift left operator
console.log(num << 0); // 123
// Bitwise XOR
console.log(num ^ 0); // 123

18. Replace all

var string = "john john";
console.log(string.replace(/hn/, "ana")); // "joana john"
console.log(string.replace(/hn/g, "ana")); // "joana joana"

tip: String.replace() function allows you to replace a string with a string or regular expression. This function only replaces the string that appears for the first time. However, you can use / g in the regular expression to simulate the function of replaceAll():

19. Use Object.is() for comparison

Object.is(0 , 0); // true

20. Get unique value from array

let uniqueArray = [...new Set([1, 2, 3, 3,3,"school","school",'ball',false,false,true,true])];
    console.log(uniqueArray) // [1, 2, 3, 'school', 'ball', false, true]

21. Sorting number array

console.log([0,10,4,9,123,54,1].sort((a,b) => a-b)) //  [0, 1, 4, 9, 10, 54, 123]

tip: JavaScript array with built-in sort method. By default, this sort method converts array elements to strings and lexicographically sorts them. This can cause problems when sorting arrays of numbers. Therefore, here is a simple solution to this problem.

22. Disable right button

< body oncontextmenu = " return false" >    < div > < / div>< / body>

You may have wanted to prevent users from right clicking on your web page. Although this is rare, in some cases you may need this feature.

Keywords: Javascript Front-end

Added by ShashidharNP on Sat, 30 Oct 2021 11:05:27 +0300