“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

The preface

These are the bits and pieces of coding skills THAT I have memorized since the moment I started moving bricks. When I look back, I realize that it is not enough to read in a short period of time. I will share some of them with you at random in the hope that they will bring you the joy of harvest. No matter how arrogant you are at this moment, but a few years later when looking back will still feel once you are how ridiculous and naive, but it is this bit of ridiculous and naive achievement of the best you. As with growth, so with technology.

Short step, not even thousands of miles; Do not accumulate small streams, beyond into rivers and seas. Every little bit will make the best of you!

Cong cong flowers, flowers gift jun; If you smile, leave praise and love.

By learning these Coding tips, you can not only make your Coding quality to a higher level, but also make your Coding speed to the rocket!!

Coding tricks

Object deconstruction of arrays

Use object destructuring to assign an array item to a variable:

const str = "1997,kangkang,boy,23"
const {1:name,2:sex,0:age} = str.split(', ')
console.log(name,sex,age) //kangkang boy 1997
Copy the code

Note: In this example, 2 is the array index after split, and sex is the specified variable with the value boy

Creating a pure object

Create an object and print it out like this

const obj = {}
console.log(obj)
console.log(obj.constructor)
console.log(obj.toString)
console.log(obj.hasOwnProperty)
Copy the code

Creates a 100% pure object that does not inheritObjectAny properties and methods (e.g constructor.toString() Etc.) :

const obj = Object.create(null)
console.log(obj)/ / {}
console.log(obj.constructor)//undefined
console.log(obj.toString)//undefined
console.log(obj.hasOwnProperty)//undefined
Copy the code

ValueOf that you haven’t seen

const obj = {
    i:1.valueOf:function(){
        if(this.i === 1) {this.i ++
            return 1
        }else{
            return 2}}}if(obj==1&&obj==2) {console.log(obj)
}
Copy the code

One object can be equal to two values. Guess if this console.log(obj) will execute? What will be the end result? (This is likely to come up in interview questions)

To summarize, I believe you have the answer:

Empty and truncate arrays

I have an array down here, and now I want to intercept the first five, how do I do that

const arr = [1.2.3.4.5.6.7.8.9]
Copy the code

At this point you might think of slice() and splice()

slice()

Slice (start,end) takes two arguments (start required,end optional), both of which are indexes, and the return value does not include end

const arr = [1.2.3.4.5.6.7.8.9]
const arr2 = arr.slice(0.5)
console.log(arr2)/ / [1, 2, 3, 4, 5]
Copy the code

splice()

To add or remove data from an array, return only the deleted data of type array (alter array)

const arr = [1.2.3.4.5.6.7.8.9]
arr.splice(5)
console.log(arr)/ / [1, 2, 3, 4, 5]
Copy the code

The easiest way to empty and truncate an array is to change the length property

const arr = [1.2.3.4.5.6.7.8.9]
arr.length = 5
console.log(arr)/ / [1, 2, 3, 4, 5]
arr.length = 0// Empty the array
Copy the code

Sum all the values in the array

The first thought might be to use a cycle, but that would be wasteful.

var numbers = [3.5.7.2];
var sum = numbers.reduce((x, y) = > x + y);
console.log(sum); // returns 17
Copy the code

Short circuit conditions

Here is the code that is often written

if (hungry) {
    goToFridge();
}
Copy the code

We can further simplify the code by using both variables and functions:

hungry && goToFridge()
Copy the code

Use OR logic for conditions

Previously, variables were declared at the beginning of a function just to avoid encountering undefined in the event of an unexpected error.

function doSomething(arg1){
    arg1 = arg1 || 32; // if it's not already set, arg1 will have 32 as a default value
}
Copy the code

Comma operator

Write this out, colleagues will certainly ask you.

let x = 1;
x = (x++, x);
console.log(x);
// expected output: 2
x = (2.3);
console.log(x);
// expected output: 3
Copy the code

Extension operator

Easily remove duplicates from an array:

const removeDuplicate = arr= >[...new Set(arr)]
let result = removeDuplicate([42.42.'11'.'11'.true.true.null.null])
console.log(result)//[42, "11", true, null]
Copy the code

Use the extension operator to flattize two-dimensional arrays quickly:

const arr = [1[2.3], [4.5]]
constflatArr = [].concat(... arr)console.log(flatArr)//[1, 2, 3, 4, 5]
Copy the code

Unfortunately, the above technique only works with two-dimensional arrays, but using recursion, we can flatten any latitude array:

function flattenArray(arr){
    constflatArr = [].concat(... arr)return flatArr.some(item= >Array.isArray(item))? flattenArray(flatArr):flatArr }const arr = [1[2.3], [4.5[6.7[8.9]]]]
console.log(flattenArray(arr))//[1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

Dynamic attribute name

const dynamic = 'flavour';
var item = {
    name: 'Coke',
    [dynamic]: 'Cherry'
}
console.log(item); 
// { name: "Coke", flavour: "Cherry" }
Copy the code

Object to an array

// Note that the object must be in the following format to be converted to an array in this way
// The DOM collection obtained and arguments for the function can also be converted to an array in this way
var obj = {
    0: 'qian'.1: 'long'.2: 'chu'.3: 'tian'.length: 4
}
var objArr = Array.prototype.slice.call(obj);
// var objArr = [].slice.call(obj);
// var objArr = Array.prototype.slice.apply(obj);
console.log(objArr)
Copy the code

Gets the maximum or minimum value in an array

function maxAndMin(arr){
    return {
       max:Math.max.apply(null,arr),
       min:Math.min.apply(null,arr)
    }
}
Copy the code

Determine whether two arrays are the same

/** * Check whether the array is the same *@param {Array} array1
 * @param {Array} array2* /
export function scalarArrayEquals(array1, array2) {
  return array1.length === array2.length && array1.every(function(v, i) { return v ===array2[i]})
}
Copy the code

Completely shield the right mouse button

Oncontextmenu ="window.event.returnValue=false< table border oncontextMenu =return(false)>< td>no< /table> Can be used for tableCopy the code

Deselect and prevent replication

< body onselectstart ="return false">Copy the code

JS does not allow pasting

Onpaste ="return false"Copy the code

JS to prevent replication

Oncopy ="return false;" Oncut ="return false;"Copy the code

The input method is disabled

< input style = "ime - mode: disabled" >Copy the code

Prevent being framed by people

if(top.location ! = self.location)top.location=self.location;Copy the code

Web pages are not saved as

< no>< iframe src=*.html>< /iframe>< /no>
Copy the code

The best way to keep your nose clean

JavaScript null-value merge operator

The number on the right is returned only if the left is null and undefined

  • Null merge operator (??) Is a logical operator that returns the right-hand operand if the left-hand operand is null or undefined, and the left operand otherwise.

  • With the logical or operator (| |), logical or operator will be on the left operand is false value returns the right operand. That is to say, if you use the | | to set default values for certain variables, may encounter unexpected behavior. For example, is false (for example, “” or 0). See the example below.

let str = null||undefined
let result = str??'You look good'
console.log(result)// You look good

const nullValue = null;
const emptyText = ""; // Empty string, is a false value, Boolean("") === false
const someNumber = 42;

const valA = nullValue ?? "Default value for valA";
const valB = emptyText ?? "Default value for valB";
const valC = someNumber ?? 0;

console.log(valA); // "default value for valA"
console.log(valB); // "" (null string is false, but not null or undefined)
console.log(valC); / / 42
Copy the code

The javaScript optional chain operator (? .).

The optional chain operator (? .) allows the value of properties deep in the chain of connected objects to be read without explicitly verifying that each reference in the chain is valid. ? The. Operator functions like the.chain operator, except that it does not cause an error if the reference is nullish (null or undefined) and the expression shorts the return value

const demo = {
    name: 'Alice'.cat: {
        name: 'Dinah'}};console.log(dog.dog); // Normal output will directly report an error
console.log(demo.someNonExistentMethod());
Copy the code

Use the optional chain operator (? Browser will not appear error!

const demo = {
    name: 'Alice'.cat: {
        name: 'Dinah'}};console.log(demo.dog? .name);// expected output: undefined
console.log(demo.what? . ());// expected output: undefined
Copy the code

Function call:

letresult = someOne.customMethod? . ();Copy the code

If you want to allow someOne to also be null or undefined, then you need to write someOne like this? .customMethod? . ()

Optional chains and expressions:

letnestedProp = obj? .'prop' + 'Name'];
Copy the code

Optional chain access array:

letarrayItem = arr? .42];
Copy the code

Short circuit calculation:

let potentiallyNullObj = null;
let x = 0;
letprop = potentiallyNullObj? .[x++];console.log(x); // X will not be incremented and will still print 0

// When using optional chains in an expression, if the left-hand operand is null or undefined, the expression will not be evaluated
Copy the code

Optional chain operation:

let customer = {
  name: "Carl".details: {
    age: 82.location: "Paradise Falls" // Details' address property not defined}};let customerCity = customer.details?.address?.city;

/ /... Optional chains can also be used with function calls
letduration = vacations.trip? .getTime? . ();Copy the code

The null merge operator can be set to a default value when using optional chains:

let customer = {
  name: "Carl".details: { age: 82}};letcustomerCity = customer? .city ??"China";
console.log(customerCity);  // "China"
Copy the code

The actual project can be used in a lot of places oh ~ back-end interface problems of the pot, I front pretty boy not back!!

Write in the last

I am Liangcheng A, a front end, who loves technology and life.

I’m glad to meet you.

If you want to learn more, please click here and look forward to your little ⭐⭐

  • Feel free to correct any mistakes in the comments section, and if this post helped you, feel free to like 👍 and follow 😊

  • This article was originally published in Nuggets and cannot be reproduced without permission at 💌