Taking advantage of the good weekend, Xiaobian struggled to get up from bed and decided to do a systematic integration of some methods often used in daily front-end programming.

Some people may think that just forget about Baidu, no no no! This thing small make up really close practice many times, Baidu once remember good, remember the next time also have to find Baidu is to pull low work efficiency.

This sorting hope can help to the need of children’s shoes, leisure boring see a few eyes to ensure that can remember (remember not to welcome the lower stamp xiaobian, Xiaobian must send “slippers” to you). Since there are always new ways to play with js methods (techniques), this document will continue to be updated.


Array

New to the Set ()

Used to de-duplicate an array.

Const arr =,4,4,5,4,6,5,7 [3]; console.log(new Set(arr)); / /,4,5,6,7 {3} const a = Array. The from (new Set (arr)) / / [3, 4, 5, 6, 7)Copy the code

Sort ()

Sort the elements of an array.

Const arr =,4,4,5,4,6,5,7 [3]; console.log(arr.sort()) // [3, 4, 4, 4, 5, 5, 6, 7]Copy the code

The reverse ()

Invert the elements in an array.

Const arr =,4,4,5,4,6,5,7 [3]; conosle.log(arr.reverse()); // [7, 6, 5, 5, 4, 4, 4, 3]Copy the code

delete

Deleting a member of an array leaves an empty space and does not affect the length attribute. The same applies to objects.

// array const arr = [3,4,4,5,4,6,5,7]; delete arr[1]; conosle.log(arr); / / [3, empty, 4, 5, 4, 6, 5, 7] / / const object obj = {name: 'pboebe, age:' 23 'sex:' female '}; delete obj.sex; console.log(obj); // {name: "pboebe", age: "23"}Copy the code

The shift ()

Remove the first element from the array and return the value of the first element.

Const arr =,4,4,5,4,6,5,7 [3]; const a = arr.shift(); // 3 console.log(arr); // [empty, 4, 5, 4, 6, 5, 7]Copy the code

Unshift ()

Adds one or more elements to the beginning of an array and returns the new length (changing the original array).

Const arr =,4,4,5,4,6,5,7 [3]; const a = arr.unshift(8); console.log(a); // 9(a is the new length of the returned array) console.log(arr); // [8, 3, 4, 4, 5, 4, 6, 5, 7]Copy the code

Push ()

Adds one or more elements to the end of an array and returns the length of the array after the new element is added.

Const arr =,4,4,5,4,6,5,7 [3]; Const a = arr. Push (8, 9); console.log(a); // 10(a is the new length of the returned array) console.log(arr); [3, 4, 4, 5, 4, 6, 5, 7, 8, 9]Copy the code

The valueOf ()

Returns the array itself.

Const arr =,4,4,5,4,6,5,7 [3]; console.log(arr.valueOf()); / /,4,4,5,4,6,5,7 [3]Copy the code

The toString ()

Converts values to strings.

Const arr =,4,4,5,4,6,5,7 [3]; console.log(arr.toString()); / / 3,4,4,5,4,6,5,7Copy the code

Concat ()

New data is formed by adding additional data to the end of the original data (for strings).

// array const a = [1,2,3]; Const b = (4, 5); const c = a.concat(b); // [1, 2, 3, 4, 5] const y = 'def'; const z = x.concat(y); // abcdefCopy the code

The join ()

Return all the parameters as a string (commas separated by default).

Const arr =,4,4,5,4,6,5,7 [3]; console.log(arr.join('-')); / / 3-4-4-3-4-4-5-7Copy the code

Slice (start, end)

Used to extract a part of the original array, returns a new extracted array, the original array unchanged (strings apply, not including end).

// array const arr = [3,4,4,5,4,6,5,7]; const a = arr.slice(2, 5); // [4, 5, 4] // String const x = 'abcdefgh'; const y = x.slice(3, 6); // defCopy the code

Splice ()

Use to delete a part of the original array, and you can add a new array member at the deletion location. The returned value is the deleted array element. (Change the array)

Splice (t, v, s) t: start position of the element to be deleted; V: number of deleted elements; S :s and the following elements are the inserted new elements.

Const arr =,4,4,5,4,6,5,7 [3]; const a = arr.splice(3, 2, 12); // [5, 4] console.log(arr); // [3, 4, 4, 12, 6, 5, 7]Copy the code

The map ()

Iterate over the members of the group, returning a new array based on the result of the iterate. The map method also applies to strings, but cannot be called directly. You need to use it indirectly through the function’s call method, or if you first convert the string to an array and then use it again.

Const arr =,4,4,5,4,6,5,7 [3]; const a = arr.map(item => item*2;) // [6, 8, 8, 10, 8, 12, 10, 14]Copy the code

The forEach ()

Similar to the map method, it traverses the array, except that it returns no value.

Const arr =,4,4,5,4,6,5,7 [3]; arr.forEach(function(value,index,arr){console.log(value)})) //3 4 4 5 4 6 5 7Copy the code

For (in)

Similar to the map method, iterates over objects or arrays.

But it’s worth noting that the values returned by the for in loop are the key names of the data structures. Iterating over the key value of the object returned by the object, iterating over the key of the array returned by the array.

// Const obj = {a: 123, b: 12, c: 2}; For (let a in obj) {console.log(a)} // a b c // array const arr = [3,4,4,5]; for(let a in arr) { console.log(a) } // 0 1 2 3Copy the code

The filter ()

A filter method that takes a function as an argument and executes all the array members in turn. The members that return true form a new array to return. (Does not change the original array).

Const arr =,4,4,5,4,6,5,7 [3]; const a = arr.filter(item => item % 3 > 1); console.log(a); / / (5, 5]Copy the code

Some () & every ()

These two methods are similar to “assert” to determine whether an array member meets a condition.

Const arr =,4,4,5,4,6,5,7 [3]; console.log( arr.some( function( item, index, array ){ console.log( 'item=' + item + ',index='+index+',array='+array ); return item > 3; })); / / item = 3, the index = 0, array = 3,4,4,5,4,6,5,7 / / item = 4, index = 1, array = 3,4,4,5,4,6,5,7 / / true console. The log (arr. Every ( function( item, index, array ){ console.log( 'item=' + item + ',index='+index+',array='+array ); return item > 3; })); / / item = 3, the index = 0, array = 3,4,4,5,4,6,5,7 / / falseCopy the code
The some method returns true as long as one of the array members returns true, otherwise false;
The every method returns true if each value is true, otherwise false;

Reduce ()

Each member of the array is processed in turn, eventually accumulating to a single value.

Format:

Reduce (() => (pre, curIndex, arr), curIndex);

Pre: Required, accumulated variables; Cur: required, current variable; CurIndex: Optional, current location; Arr: Optional, raw array; InitialValue: the initialValue passed to the function.

// const arr = [3,4,4,5,4,6,5,7]; Const a = arr.reduce((pre, cur) => {return pre+cur}) const a = arr.reduce((pre, cur) => {return pre+cur}) Sum)) console.log (a) // 38 // advanced usage (e.g. array deduplicate and array flatten) const b = arr.reduce((pre, cur) => {if(! } else {return pre}}, []) // [3, 4, 5, 6, 7] const arrs = [[2,3,2] [three, four, five]] const c = arr. Reduce ((pre, cur) = > {return the pre. Concat (cur)}, []) / / [2, 3, 2, 3, 4, 5]Copy the code

There are many other ways to use reduce.

ReduceRight ()

The reduceRight method is used in the same way as the Reduce method. The difference is that the reduceRight method is executed from right to left (the example is skipped).

IndexOf ()

Returns the first occurrence of the given element in the array, or -1 if not (also for strings).

// array const arr = [3,4,4,5,4,6,5,7]; Console. log(arr.indexof (4)) // 1 console.log(arr.indexof ('4')) // -1 // String const string = 'asdfghj'; console.log(string.indexOf('a')) // 0Copy the code

The lastIndexOf ()

Returns the last occurrence of the given element in the array, without -1(also for strings).

Const arr =,4,4,5,4,6,5,7 [3]; Console. log(arr.lastIndexof (4)) // 4Copy the code

GroupBy ()

Group the elements of the collection by key, which is returned by the argument passed in.

Const arr = [{name: xiao Sun, age: 18, score: 60, weight: 60}, {name: xiao Wang, age: 19, score: 70, weight: 55}, {name: 'Xiao Li ', age: 18, score: 60, weight: 70}, {name:' Xiao Liu ', age: 20, score: 70, weight: 65}, {name: 'Xiao Zhao ', age: 18, score: 60, weight: 65}, {name:' Xiao Zhao ', age: 18, score: 65}, 60, weight: 60}, {name: 'xiaoqian ', age: 19, score: 70, weight: 55}, {name:' xiaozhou ', age: 20, score: 60, weight: 50},]; const example = (data, key) => { return data.reduce(function(prev, cur) { (prev[cur[key]] = prev[cur[key]] || []).push(cur); return prev; }, {}); }; console.log(example(arr, 'age')); // Object: {18: Array(3), 19: Array(2), 20: Array(2)} 18: Array(3) 0: {name: "sun ", age: 18, Score: 60, weight: 60} 1: {name: "xiao Li ", age: 18, score: 60, weight: 70} 2: {name:" xiao Zhao ", age: 18, score: 60, weight: 60} 19: Array(2) 0: {name: "xiao Li ", age: 18, score: 60, weight: 70} 1: {name: "xiao Qian ", age: 19, score: 70, weight: 55} 1: {name:" xiao Qian ", age: 19, score: 70, weight: 55} 20: Array(2) 0: {name: "Xiao Liu ", age: 19, score: 70, weight: 55} 20, score: 70, weight: 65} 1: {name: "xiao zhou ", age: 20, score: 60, weight: 50} 2: {name:" xiao zhou ", age: 20, score: 60, weight: 50}Copy the code

The shuffle ()

Shuffling a set randomly.

Const arr =,2,3,4,5,6,7,8,9,10 [1]; const shuffle = ([...arr]) => { let m = arr.length; while (m) { const i = Math.floor(Math.random() * m--); [arr[m], arr[i]] = [arr[i], arr[m]]; } return arr; }; console.log(shuffle(arr)) // [10, 9, 7, 5, 6, 4, 1, 2, 8, 3]Copy the code

Flatten ()

Flat (), receives an array, and no matter how many arrays are nested in that array, Flatten eventually turns it into a one-dimensional array (flattening).

Const arr = [[1, 2, 3], [4, 5, [6, 7]]]. const a = arr.flatten(3); console.log(a); // [1, 2, 3, 4, 5, 6, 7]Copy the code

Array. IsArray ()

To determine whether the data is an array, return true or false.

Const arr =,4,4,5,4,6,5,7 [3]; console.log(Array.isArray(arr)) // trueCopy the code

CopyWithin ()

Copies elements from a specified location in an array to another specified location in the array.

Array. CopyWithin (target, start, end)

Const arr =,4,4,5,4,6,5,7 [3]; The console. The log (arr. CopyWithin (4, 2)) / / [3, 4, 4, 5, 4, 5, 4, 6]Copy the code

The find ()

Returns the array elements that match the conditions passed to the test.

Const arr =,4,4,5,4,6,5,7 [3]; const a = test.find(item => item > 3); console.log(a); //4(the find() method returns the value of the first element of the array tested.) const b = test.find(item => item == 0); console.log(b); //undefined(return undefined if there are no qualified elements)Copy the code

String

CharAt ()

The character used to return the specified position.

const str = 'hello guys';
console.log(str.charAt(3))  // l
Copy the code

CharCodeAt ()

Used to return the Unicode encoding of the character at the specified position.

const str = 'hello guys';
console.log(str.charCodeAt(3))  // 111
Copy the code

Match ()

Used to retrieve a specified value within a string or to find a match of one or more regular expressions, returning the value rather than its position.

const str = 'hello guys'; Console. log(str.match('guys')) // ["guys"] // Use regular match string const STRS = '1. Hello guys, 2. Are you OK? '; console.log(strs.match(/\d+/g)) // ["1", "2"]Copy the code

The replace ()

Replace the matched string.

const str = 'hello guys';
console.log(str.replace('guys', 'man'))  // hello man
Copy the code

Draws a specified character from the string.

const str = 'AA_BB_CC.bin'; The console. The log (STR. Replace (/ / ^ \ _ / g), ' ') / / __ (underlined)Copy the code

Search ()

It is used to retrieve a substring that matches a string, returning the address. The difference with indexOf() is that search enforces regex, while indexOf just matches by string.

const str = 'hello guys'; Console.log (str.search('guys')) // 6 console.log(str.indexof ('guys')) // 6 // distinguished const string = 'abcdefg.1234'; Console.log (string.search(/\./)) // 7 Console.log (string.indexof (/\./)) // -1Copy the code

The split ()

Cut the string into an array.

const str = 'hello guys';
console.log(str.split('')) // ["h", "e", "l", "l", "o", " ", "g", "u", "y", "s"] 
console.log(str.split('', 3)) //  ["h", "e", "l"]
Copy the code

ToLocaleLowerCase () & toLowerCase ()

Converts a string to lowercase.

const str = 'hello guys';
console.log(str.toLocaleLowerCase())  // hello guys
console.log(str.toLowerCase())  //  hello guys

Copy the code

ToLocaleUpperCase () & toUpperCase ()

Converts the string to uppercase.

const str = 'hello guys';
console.log(str.toLocaleUpperCase())  // HELLO GUYS
console.log(str.toUpperCase())  // HELLO GUYS

Copy the code

The substr ()

Used to extract the specified number of characters in a string from the starting index number.

const str = 'hello guys';
console.log(str.substr(2))  // llo guys
console.log(str.substr(2, 7))  // llo guy
Copy the code

The substring ()

Used to extract the character in a string between two specified index numbers. Unlike the slice() and substr() methods, substring() does not accept negative arguments.

const str = 'hello guys';
console.log(str.substring(2))   // llo guys
console.log(str.substring(2, 7))  //  llo g
Copy the code

The trim ()

Remove Spaces at both ends of the string.

const str = ' hello guys '; Console.log (str.trim()) // Hello Guys (does not change the array)Copy the code

The common json.xxx method

JSON. The parse ()

Used to convert strings to objects.

const str = '{"name": "phoebe", "age": 20}'; Parse (STR) // {name: "phoebe", age: 20} (object type)Copy the code

JSON. Stringify ()

Used to convert objects to strings.

const obj = {"name": "Tins", "age": 22}; Const STR = json.stringify (obj) // {"name":"Tins","age":22}(string)Copy the code

There are six methods for an Object instance

Object. The Prototype. The valueOf ()

Returns the value of the current object. (object.valueof () is equivalent to object.prototype.valueof ())

Let’s create a function that replaces the valueOf() method, but note that the method must pass no arguments. Let’s say we have an object called ObjectrType and I want to create a valueOf() method for it. The following code assigns a custom function to the valueOf() method:

ObjectrType.prototype.valueOf = function() { return customValue; };
Copy the code

With such a method, the next time ObjectrType is to be converted to a primitive type value, JavaScript will automatically call the custom valueOf() method until then. The valueOf() method is usually called automatically by JavaScript, but we can also call it ourselves like this:

ObjectrType.valueOf()
Copy the code

ValueOf also applies to string, number, symbol, Boolean, date.

Object. The Prototype. The toString ()

Returns the string form of the current object.

function Dog(name) {
  this.name = name;
}

const dog1 = new Dog('Gabby');

Dog.prototype.toString = function dogToString() {
  return '' + this.name;
}

console.log(dog1.toString());  // Gabby
Copy the code

Object. The Prototype. ToLocaleString ()

Returns the module string corresponding to the current object.

Grammar: obj. ToLocaleString ();

let foo = {};
foo.toLocaleString(); // "[object Object]"
Copy the code

Object. The Prototype. IsPrototypeOf ()

Determines whether the current object is a prototype of another object. Grammar: Object. The prototype. IsPrototypeOf (targetObj)

const arr = []; Array.prototype.isPrototypeOf(arr); Object.setprototypeof (arr, string.prototype); Array.prototype.isPrototypeOf(arr); // false String.prototype.isPrototypeOf(arr); // trueCopy the code

Object. The Prototype. The hasOwnProperty ()

Determines whether an attribute is a property of the current object itself, or a property inherited from the prototype object, and returns a Boolean value.

Grammar: Object. The prototype. HasOwnProperty (prop)

let obj = {}; // Define an object instance obj.prop1 = 'value1'; / / prop1 is a self-owned property obj. Constructor. Prototype. Prop2 = 'value2'; // Prop2 is a prototype chain property // We can access console.info(obj.prop1) whether we have the own property or the prototype chain property; // value1 console.info(obj.prop2); // value2 // Use the 'hasOwnProperty()' method to determine whether the property is its own obj. HasOwnProperty ('prop1'); // true obj.hasOwnProperty('prop2'); // falseCopy the code

Object. The Prototype. PropertyIsEnumerable ()

Determines whether an attribute is enumerable.

Grammar: Object. The prototype. PropertyIsEnumerable (prop)

const obj = { name: 'ecmaer'}; Object.getOwnPropertyDescriptor(obj, 'name').enumerable; // true obj.propertyIsEnumerable('name'); Object.defineproperty (obj, 'name', {enumerable: false}); obj.propertyIsEnumerable('name'); // false for(let i in obj){ console.info(obj[i]); // not traversing 'ecmaer'}Copy the code

Javascript’s three ways to determine the type of a value

TypeOf ()

Typeof can be used to detect data types: note that Typeof does not distinguish between null, Array, and object in general.

typeof 123 //number typeof '123' //string typeof true // boolean typeof false //boolean typeof undefined // undefined Typeof math. abs // function typeof function () {} // function // returns object Typeof when 'null', 'Array', and 'object' are encountered Null // object typeof [] // object (array.isarray (arr)) typeof {} // object // when the data uses the new keyword and the wrapper object, Data becomes Object and is treated as a normal function without the new keyword. typeof new Number(123); //'object' typeof Number(123); // 'number' typeof new Boolean(true); //'object' typeof Boolean(true); // 'boolean' typeof new String(123); // 'object' typeof String(123); // 'string'Copy the code

InstanceOf ()

The instanceOf () operator checks whether the constructor’s prototype property is present in the prototype chain of an instance object

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);

console.log(auto instanceof Car); // true
console.log(auto instanceof Object); // true
Copy the code

Object. The Prototype. The toString () (recommended)

Can accurately determine the object type.

For array, NULL and object, the relationship between them is intricate and complex. Using Typeof will return object string uniformly. To distinguish objects, arrays and functions, it is not possible to simply use Typeof, and to accurately determine the object type, It is recommended to use the Object. The Prototype. The toString (), it can be judged an Object value belongs to the kind of built-in types.

Const arrs = [1, 2, 3]; console.log(typeof arrs) // object console.log(Object.Prototype.toString.call(arrs)) // [object Array]Copy the code

Use of call, apply, and bind

usage

  • call

    Calls the execution function directly and, when executed, binds the scope inside the function to the specified scope. (The call() method takes a list of several parameters.)

    Const arr = const,5,4,7,6 [2] a = Function. The prototype. Apply. Call (Math. Max, null, arr) console. The log / / 7 (a)Copy the code
  • apply

    Calls the execution function directly and, when executed, binds the scope inside the function to the specified scope.

    Call () is a syntactic sugar for apply(). It works just like apply() and can be inherited. The only difference is that call() receives a list of arguments, whereas apply() receives an array of arguments.

    Const arr = const,5,4,7,6 [2] a = Function. The prototype. Call. Apply (Math. Max, Arr) console.log(a) // 7 Returns - Infinity const b = Function. The prototype. Call. Apply (Math. Max, null, arr) console. The log (b) / / - InfinityCopy the code
  • bind

    Creates a reference to a new function, bound to a scope-specific scope, and supports passing parameters.

    Bind uses the same function as call, except that call and apply call the function immediately, and bind binds this

    Format: bind(scope parameter, parameter 1, parameter 2)

    const fruits = {
        "name": "apple",
        getOtherFriut: function() {
            return this.name;
        }
    }
    
    const color = {
       "name": " is red" 
    }
    
    const fruitColor = fruits.getOtherFriut.bind(this, color)
    console.log(fruitColor()) //is red
    
    Copy the code

The similarity

  • It’s all about changing the functionthisObject;
  • The first argument is boththisObject to point to;
  • Can be passed by the following parameters;

The difference between

  • Can be used to call a method instead of another object, changing the object context of a function from its original context tothisObjThe specified new object.
  • bind()Returns a new function to be called later, whereasapply()andcall()Is called immediately.
  • call()andapply()The only difference is the parameters,call()isapply()Grammar sugar;

Choose to use

  • If you do not need to care how many parameters are passed into the function, selectapply();
  • If you want to determine how many parameters a function can accept, and you want to clearly express the relationship between parameters and arguments, usecall();
  • Use if you want to call the method again in the future without immediately getting the result from the functionbind();

The use of Date objects

First you need to define a variable:

const date = new Date();

Next, you can directly use the common Date object methods.

  • Date(): Return the Date and time of the day;
  • GetDate (): Returns a day in a month from the Date object (1 to 31)console.log(date.getDate());
  • GetDay (): returns a day of the week (0-6) from the Date object;
  • GetMonth (): Returns the month (0 to 11) from the Date object.
  • GetFullYear (): Returns a four-digit year from a Date object;
  • GetYear () : you can use getFullYear() instead;
  • GetHours (): returns the hour of the Date() object (0 ~ 23);
  • GetMinutes (): returns the minutes of the Date() object (0 ~ 59);
  • GetSeconds (): returns the minutes of the Date() object (0 ~ 59);
  • GetMillseconds (): returns the milliseconds (0 ~ 999) of the Date() object;
  • GetTime (): returns the date from January 1, 1970 to the present;
  • GetTimezoneOffset (): Returns the minute difference between the local time and Greenwich Mean Time (GMT).
  • GetUTCDate (): Returns a day (1-31) in the month from the Date object according to universal time.
  • GetUTCDay (): Returns the day of the week (1-6) from the Date object according to universal time;
  • GetUTCMonth (): returns the month (0 to 11) from the Date object based on universal time.
  • GetUTCFullYear (): Returns a four-digit year from the Date object according to universal time;
  • GetUTCHours (): The hour (0 ~ 23) to return the object from the Date object according to universal time;
  • GetUTCMinutes (): The number of minutes (0 ~ 59) to return an object from the Date object according to universal time.
  • GetUTCSeconds (): The number of seconds (0-59) returned from the Date object according to universal time;
  • GetUTCMillseconds (): Returns the milliseconds (0-999) of the object from the Date object in universal time;
  • Parse (): Returns the number of milliseconds between midnight on January 1, 1970, and the specified date (string);
  • SetDate (): Sets a day (1 to 31) in the month of the Date object.
  • SetMonth (): Sets the month (0 to 11) in the Date object.
  • SetFullYear (): Sets the year (four digits) in the Date object;

Methods beginning with math.xx

  • Math.ceil(): Rounding up logarithms (ceiling function)

Is greater than or equal to x, and its nearest integer.

  • Math.floor(): Rounds down logarithms (floor function).
  • Math.max(x,y): returns the maximum value in x,y.
  • Math.min(x,y): returns the minimum value in x,y.
  • Math.pow(x,y): returns x to the y power.
  • Math.random() : Returns a random number between 0 and 1.
  • Math.round(x): Round (x).
  • Math.abs(x): Returns the absolute value of the number.
  • Math.acos(x): Returns the arc cosine of the number.
  • Math.asin(x): Returns the arc sine of the number.
  • Math.atan(x): Returns the inverse tangent of the number.
  • Math.atan2(y,x): Returns the Angle in radians from the X-axis to the point (x, y).
  • Math.cos(x): Returns the cosine of the number.
  • Math.exp(e): Returns the exponent of e.
  • Math.log(x): Returns the natural logarithm (base e) of the number.
  • Math.sin(x): Returns the sine of the number.
  • Math.sqrt(x): Returns the square root of the number.
  • Math.tan(x): Returns the tangent of the Angle.
  • Math.tosource (): Returns the source code for this object.
  • Math.valueof (): returns the original valueOf the Math object.

One more 😤 : simple array de-duplicate

There is a simple way to deduplicate an array. The following is a simple way to deduplicate an array. There are several ways to deduplicate an array.

[…new Set(arr)]

Const arr =,5,3,4,6,5,8,6 [4]; console.log(Array.from(new Set(arr))) // [4, 5, 3, 6, 8] console.log([...new Set(arr)]) // [4, 5, 3, 6, 8]Copy the code

Recude + include to heavy

Const arr =,5,3,4,6,5,8,6 [4]; const a = arr.reduce((prev,cur) => prev.includes(cur) ? prev : [...prev,cur],[]); console.log(a) // [4, 5, 3, 6, 8]Copy the code

Use filter to remove weight

Const arr =,5,3,4,6,5,8,6 [4]; const b = arr.filter((item, index, arr) => arr.indexOf(item, 0) === index;) // [4, 5, 3, 6, 8]Copy the code

Use hasOwnProperty to deduplicate

Const arr =,5,3,4,6,5,8,6 [4]; function duplicate (arr) { var obj = {}; return arr.filter(function(item, index, arr){ return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true) }) } console.log(duplicate(arr)) // 4, 5, 3, 6, 8]Copy the code

There are only a few simple and safe ways to do this. Other ways to do this are to consider using recursion and map data structures.

There may be children think can also use includes,sort,indexOf and other ways to redo,in fact, is also possible, but pay attention to these ways for complex one-dimensional array to redo, there may be some bugs, but also need to deal with their own.

So, can master the above several simple way to redo, when necessary will save a lot of time.


Second shift 😤 : convenient Lodash

Lodash, a consistent, modular, high-performance JavaScript utility library. This is the small editor in a recent project, processing data stumbled upon, using it to deal with data write a lot less code, a very useful tool library, can pick.

Attach a link: www.lodashjs.com/docs/lodash…

Tidy up so far, please remember !!!! (remember not welcome below 👇 stamp xiaobian, Xiaobian to send you “slippers”) 🤨


conclusion

Here is the basic comb finished, the more small knowledge more to master (pressctl+fFind it and you’ll be surprised (Maciscommand+f) can be quickly searched). After no accident will xiaobian two weeks more, this comb, will continue to updateing.(dark poke attached bestie male god figure hope not to be seen hey hey)