Array to heavy

Normally we implement arrays to be more important through a double layer traversal or indexOf.

doubleforCycle to heavy

    function unique(arr) {
      for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i] == arr[j]) {
            arr.splice(j, 1);
            j--;
          }
        }
      }
      return arr;
    }
Copy the code

usingindexOfduplicate removal

function unique(arr) { if (! Array.isArray(arr)) { console.log("type error!" ); return; } var array = []; for (var i = 0; i < arr.length; i++) { if (array.indexOf(arr[i]) === -1) { array.push(arr[i]); } } return array; }Copy the code

But there’s an easier way to do this: use array. from and set

function unique(arr) { if (! Array.isArray(arr)) { console.log("type error!" ); return; } return Array.from(new Set(arr)); }Copy the code

The implementation of this code is not very simple 😉

Array to object (Array to Object) 🦑

To convert an array to an object, this is the first method that most students think of:

var obj = {};
var arr = ["1","2","3"];
for (var key in arr) {
    obj[key] = arr[key];
}
console.log(obj)

Output:
{0: 1, 1: 2, 2: 3}
Copy the code

But there’s a quick and easy way to do this:

Const arr = [1,2,3] const obj = {... arr} console.log(obj) Output: {0: 1, 1: 2, 2: 3}Copy the code

Why iterate over something that can be done in one line of code? 😛

Rational use of ternary expressions 👩👦👦

In some scenarios, we need to assign different values to variables according to different conditions. We usually use the following method:

const isGood = true;
let feeling;
if (isGood) {
  feeling = 'good'
} else {
  feeling = 'bad'
}
console.log(`I feel ${feeling}`)

Output:
I feel good
Copy the code

But why not use ternary expressions?

const isGood = true;
const feeling = isGood ? 'good' : 'bad'
console.log(`I feel ${feeling}`)

Output:
I feel good
Copy the code

This idea, known as a Single line, is that code tends to be concise.

To a numeric type (Convert to Number) 🔢

ParseInt (), Number(), parseInt(), Number()

const age = "69";
const ageConvert = parseInt(age);
console.log(typeof ageConvert);

Output: number;
Copy the code

You can also convert with + :

const age = "69";
const ageConvert = +age;
console.log(typeof ageConvert);

Output: number;
Copy the code

To a string type (Convert to String) 🔡

ToString (), String();

let a = 123; a.toString(); / / '123'Copy the code

But you can also do this with value + “” :

let a = 123; a + ""; / / '123'Copy the code

Performance tracking 🥇

If you want to test the execution time of a piece of JS code, you can try performance:

let start = performance.now();
let sum = 0;
for (let i = 0; i < 100000; i++) {
  sum += 1;
}
let end = performance.now();
console.log(start);
console.log(end);
Copy the code

Merge objects (Combining Objects) 🌊

const obj1 = { a: 1 }
const obj2 = { b: 2 }
console.log(Object.assign(obj1, obj2))

Output:
{ a: 1, b: 2 }
Copy the code

There’s actually a simpler way to do it:

const obj1 = { a: 1 } const obj2 = { b: 2 } const combinObj = { ... obj1, ... obj2 } console.log(combinObj) Output: { a: 1, b: 2 }Copy the code

That is, through the spread operator.

Short circuit operation (Short-circuit evaluation) 🥅

We can use && and | | to simplify our code, such as:

if (isOnline) { postMessage(); } // Use &&isonline &&postmessage (); / / use | | let name = null | | "forest".Copy the code

Array flattening (Flattening an array) 🍓

Array flattening, we generally use recursion or reduce to achieve

var arr = [1, [2, [3, 4]]];

function flatten(arr) {
  var result = [];
  for (var i = 0, len = arr.length; i < len; i++) {
    if (Array.isArray(arr[i])) {
      result = result.concat(flatten(arr[i]));
    } else {
      result.push(arr[i]);
    }
  }
  return result;
}

console.log(flatten(arr));
Copy the code

reduce

var arr = [1, [2, [3, 4]]]; function flatten(arr) { return arr.reduce(function (prev, next) { return prev.concat(Array.isArray(next) ? flatten(next) : next); } []); } console.log(flatten(arr));Copy the code

But ES6 provides a new method, flat(depth). Depth, which represents the depth to expand the nested array, defaults to 1

let arr = [1, [2, 3, [4, [5]]]]; arr.flat(3); / / [1, 2, 3, 4, 5]Copy the code

Exponentiation 🍜

Math.pow() = 2^10 = 2^10 = 2^10

console.log(Math.pow(2, 10));
Copy the code

The exponential operator ** was introduced in ES7, and ** has the same result as math.pow ().

console.log(2 ** 10); / / output 1024Copy the code

Conversion of floating point numbers to integers (Float to Integer) 🦊

We typically convert floating point numbers to integers using math.floor (), math.ceil (), math.round (). But there’s actually a faster way:

The console. The log (~ 6.95); // 6 console.log(6.95 >> 0); // 6 console.log(6.95 << 0); / / 6 console. The log (6.95 | 0); // 6 // >>> Cannot round negative numbers console.log(6.95 >>> 0); / / 6Copy the code

Also is to use ~, > >, < <, > > >, | these operators to realize integer

Truncation array

If you need to change the length of an array to a fixed value, try this

let array = [0, 1, 2, 3, 4, 5];
array.length = 3;
console.log(array);

Output: [0, 1, 2];
Copy the code

Gets the last item in the array 🦁

To get the last item of an array, we usually use:

let arr = [0, 1, 2, 3, 4, 5];
const last = arr[arr.length - 1];
console.log(last);

Output: 5;
Copy the code

But we can also do this with slice:

let arr = [0, 1, 2, 3, 4, 5];
const last = arr.slice(-1)[0];
console.log(last);

Output: 5;
Copy the code

Make yourJSON 💄

Json.stringify is used a lot in daily development, but it may not be clear what parameters it takes.

He has three parameters:

  • json: Yes, can be an array orObject
  • replacer: Optional value, can be an array or a method
  • space: What do you use for separation

We can specify the value of the third argument space to beautify our JSON:

Object.create(null) 🐶

In both Vue and Vuex, the authors use object.create (null) to initialize a new Object. Why not use a more concise {}? Let’s look at the definition of object.create () :

Object.create(proto,[propertiesObject])
Copy the code
  • proto: The prototype object of the newly created object
  • propertiesObject: optional. Enumerable properties to add to the new object (the newly added properties are their own properties, not those on their stereotype chain).

Let’s go through them separatelyObject.create(null)and{}Create different objects:

As you can see from the above figure, objects created by {} inherit Object’s own methods, such as hasOwnProperty, toString, etc., and can be used directly on new objects.

An Object created with Object.create(null) has no attributes on the prototype chain except its own attribute A.

Create (null) to create a pure Object. We can define hasOwnProperty, toString, etc., without overwriting any of the methods on the prototype chain.

Copy array 🐿

Copying arrays is a common scenario in everyday development. There are a lot of tricks to copying arrays.

Array.slice

const arr = [1, 2, 3, 4, 5];
const copyArr = arr.slice();
Copy the code

Expansion operator

const arr = [1, 2, 3, 4, 5];
const copyArr = [...arr]
Copy the code

useArrayConstructor and expansion operator

const arr = [1, 2, 3, 4, 5]; const copyArr = new Array(... arr)Copy the code

Array.concat

const arr = [1, 2, 3, 4, 5];
const copyArr = arr.concat();
Copy the code

Avoid multi-conditional juxtaposition 🦀

Developing sometimes will have multiple conditions, the execution of the same statement, namely multiple | | this:

if (status === 'process' || status === 'wait' || status === 'fail') {
  doSomething()
}
Copy the code

It’s not very semantically readable. Changes can be made through Switch Case or includes.

switch case

switch(status) {
  case 'process':
  case 'wait':
  case 'fail':
    doSomething()
}
Copy the code

includes

const enum = ['process', 'wait', 'fail']
if (enum.includes(status)) {
  doSomething()
}
Copy the code

Object.freeze() 🃏

When you document data binding and responses in Vue, you note that you cannot update responses to objects that have passed through the object.freeze () method. The object.freeze () method is used to freeze an Object and prevent modification of its properties.

Because of this characteristic, it has many applicable scenarios in actual projects.

For purely presentable pages, there may be large arrays or objects. If the data will not change, you can use object.freeze () to freeze them so that Vue does not perform setter or getter conversions on these objects, which can greatly improve performance.

Thank you