Array

new Set()

Used to deduplicate an array.

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

sort()

Sort array elements (changing the array).

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

reverse()

Inverts the elements of an array (changes the original array).

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

delete()

Deleting an array member creates a void and does not affect the length property. 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]
/ / object
const obj = {name: 'pboebe'.age: '23'.sex: 'woman'};
delete obj.sex;
console.log(obj); // {name: "pboebe", age: "23"}
Copy the code

shift()

Removes the first element from the array and returns the value of the first element (changing the array).

const arr = [3.4.4.5.4.6.5.7];
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 the array and returns the new length (changing the original array).

const arr = [3.4.4.5.4.6.5.7];
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 (changing the array).

const arr = [3.4.4.5.4.6.5.7];
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

valueOf()

Returns the array itself.

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

toString()

Values can be converted to strings.

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

concat()

Add additional data to the end of the original data to make up the new data (strings apply).

/ / array
const a = [1.2.3];
const b = [4.5];
const c = a.concat(b); // [1, 2, 3, 4, 5]
/ / string
const x = 'abc';
const y = 'def';
const z = x.concat(y); // abcdef
Copy the code

join()

All parameters are returned as a string (usually separated by commas by default) using arguments as delimiters.

const arr = [3.4.4.5.4.6.5.7];
console.log(arr.join(The '-')); / / 3-4-4-3-4-4-5-7
Copy the code

slice(start, end)

Used to extract part of the original array, returns an extracted new array, unchanged (strings apply, excluding 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); // def
Copy the code

splice()

Used to delete a portion of the original array, and can add a new array member at the deleted location. The return value is the deleted array element. Splice (t, v, s) t: the starting position of the element to be deleted; V: number of deleted elements; S :s and the following elements are the new elements that are inserted.

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

map()

Iterate over the members of the array, returning a new array based on the result. The map method also works with strings, but cannot be called directly. You need to use it indirectly, through the call method of the function, or by converting the string stream to an array.

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

forEach()

Similar to the map method, the array is iterated, except that no value is returned.

const arr = [3.4.4.5.4.6.5.7];
arr.forEach(function(value,index,arr){console.log(value)}))
Copy the code

for in()

Similar to the map method, it iterates through an object or array. But it’s worth noting that the values returned by the for in loop are the key-value names of the data structures. The key of the object returned by the iterator, and the key of the array returned by the iterator.

/ / object
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	3
Copy the code

filter()

A filter method that takes a function that is executed by all array members and returns true as a new array. (Does not change the original array).

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

some() & every()

These methods are similar to assert, which is used to determine whether an array member meets a condition. The some method returns true as long as one of the array members returns true, false otherwise; The every method returns true only if each value is true, otherwise false.

const arr = [3.4.4.5.4.6.5.7];
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,4,4,5,4,6,5,7 = 3
/ / item = 4, index = 1, array,4,4,5,4,6,5,7 = 3
// true
console.log( arr.every( function( item, index, array ){
	console.log( 'item=' + item + ',index='+index+',array='+array );
	return item > 3;
}));
/ / item = 3, the index = 0, array,4,4,5,4,6,5,7 = 3
//false
Copy the code

reduce()

Process each member of the array in turn, eventually accumulating a value. A: Mandatory, cumulative variable; B: Mandatory, current variable; X: Optional, current position; Y: Optional, primitive array.

// reduce(a, b, x, y)
//
const arr = [3.4.4.5.4.6.5.7];
const a = arr.reduce((pre, cur) = > {return pre+cur})
// use a comma
const a = arr.reduce((pre, cur) = > (sum= pre+cur, sum))
consoleThe (a)/ / 38
// Advanced usage (for example array deleveraging and array flattening)
const b = arr.reduce((pre, cur) = > {
	if(! pre.includes(cur)) {return pre.concat(cur)
    } else {
		return pre
    }
}, [])
// [3, 4, 5, 6, 7]
const arrs = [[2.3.2], [3.4.5]]
const c = arr.reduce((pre, cur) = > {
	return pre.concat(cur)
}, [])
// [2, 3, 2, 3, 4, 5]
Copy the code

There are many ways to use reduce, and you can try them yourself.

reduceRight()

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

let numbers = [65.44.12.4];
 
function getSum(total, num) {
    return total + num;
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);
}
Copy the code

indexOf()

Returns the position of the given element’s first occurrence in the array, or -1 if there is none (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
conststring = 'asdfghj';
console.log(string.indexOf('a')) / / 0
Copy the code

lastIndexOf()

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

const arr = [3.4.4.5.4.6.5.7];
console.log(arr.lastIndexOf(4))
// 4(last position from left to right, same with string)
Copy the code

groupBy()

The elements of the collection are grouped by key, which is returned by the passed argument.

const arr = [
    {name: 'note:'.age: 18.score: 60.weight: 60},
    {name: 'wang'.age: 19.score: 70.weight: 55},
    {name: 'xiao li'.age: 18.score: 60.weight: 70},
    {name: 'liu'.age: 20.score: 70.weight: 65},
    {name: 'xiao zhao'.age: 18.score: 60.weight: 60},
    {name: 'money'.age: 19.score: 70.weight: 55},
    {name: 'little weeks'.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: "Note".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: "Wang".age: 19.score: 70.weight: 55}
1: {name: "Money".age: 19.score: 70.weight: 55}
20: Array(2)
0: {name: "Liu".age: 20.score: 70.weight: 65}
1: {name: "Chou".age: 20.score: 60.weight: 50}
Copy the code

shuffle()

Shuffle a set randomly with a shuffle algorithm.

const arr = [1.2.3.4.5.6.7.8.9.10];
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 (). Taking an array, no matter how many arrays are nested in it, Flatten will eventually turn it into a one-dimensional array (flat).

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()

Check whether data is an array and return true or false.

const arr = [3.4.4.5.4.6.5.7];
console.log(Array.isArray(arr)) // true
Copy the code

copyWithin()

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

Format: array.copywithin (target, start, end)const arr = [3.4.4.5.4.6.5.7];
console.log(arr.copyWithin(4.2)) // [3, 4, 4, 5, 4, 5, 6]
Copy the code

find()

Returns an array element that matches the criteria of the passed test (function).

const arr = [3.4.4.5.4.6.5.7];
const a = test.find(item= > item > 3);
console.log(a); //4(the find() method returns the value of the first element of the array that passed the test.)
const b = test.find(item= > item == 0);
console.log(b); //undefined(undefined if there is no qualified element)
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()

The Unicode encoding used to return 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 for one or more regular expressions that return the value rather than the position of the value.

const str = 'hello guys';
console.log(str.match('guys'))  // ["guys"]
// Use the re to match the string
const strs = '1.hello guys, 2.are you ok? ';
console.log(strs.match(/\d+/g)) / / / "1", "2"
Copy the code

replace()

Replaces the matching string.

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

search()

A substring used to retrieve a match to a string returns an address, unlike indexOf(), where search is mandatory and indexOf only matches by string.

const str = 'hello guys';
console.log(str.search('guys'))  / / 6
console.log(str.indexOf('guys'))  / / 6
/ / the difference between
conststring = 'abcdefg.1234';
console.log(string.search(/ /. /)) // 7 (after translation can match the position of.)
console.log(string.indexOf(/ /. /)) // if you can't find it, you can only match the string.
Copy the code

split()

Slicing strings into arrays.

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 a string to uppercase.

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

substr()

The character used to extract the number in the 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

substring()

Retrieves the character between two specified index numbers in a string. (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

trim()

Remove Spaces at both ends of the string.

const str = ' hello guys ';
console.log(str.trim()) // Hello guys(will not change the original array)
Copy the code

json

JSON.parse()

Used to convert strings into objects.

const str = '{"name": "phoebe", "age": 20}';
const obj = JSON.parse(str)  // {name: "Phoebe ", age: 20} (object type)
Copy the code

JSON.stringify()

Used to convert an object to a string.

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

Object Instance objects have six main methods

Object.Prototype.valueOf()

Returns the value of the current object. ValueOf() is equivalent to Object.prototype.valueof (). We create a function that replaces the valueOf() method, but note that the method must not take 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, JavaScript automatically calls the custom valueOf() method the next time an ObjectrType is converted to a primitive value. The valueOf() method is normally called automatically by JavaScript, but we can also call it ourselves as follows:

ObjectrType.valueOf()
Copy the code

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

Object.Prototype.toString()

Returns the string representation of the current object.

functionDog(name) {
    this.name = name;
}
const dog1 = new Dog('Gabby');
Dog.prototype.toString = functiondogToString() {
    return' ' + this.name;
}
console.log(dog1.toString());  // Gabby
Copy the code

Object.Prototype.toLocaleString()

Returns the module string corresponding to the current object. Grammar: obj. ToLocaleString ();

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

Object.Prototype.isPrototypeOf()

Determines whether the current object is a prototype of another object. Grammar:

Object.prototype.isPrototypeOf(targetObj)const arr = [];
Array.prototype.isPrototypeOf(arr); // true
// Modify the obj prototype
Object.setPrototypeOf(arr, String.prototype);
Array.prototype.isPrototypeOf(arr); // false
String.prototype.isPrototypeOf(arr); // true
Copy the code

Object.Prototype.hasOwnProperty()

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

let obj = {};// Define an object instance
obj.prop1 = 'value1'; Prop1 is a property of its own
obj.constructor.prototype.prop2 = 'value2'; Prop2 is a prototype chain property
// We can access all attributes, whether they are our own or prototype chain attributes
console.info(obj.prop1); // value1
console.info(obj.prop2); // value2
// Use the 'hasOwnProperty()' method to determine whether the property is owned
obj.hasOwnProperty('prop1'); // true
obj.hasOwnProperty('prop2'); // false
Copy the code

Object.Prototype.PropertyIsEnumerable()

Determines whether an attribute is enumerable.

const obj = { name: 'ecmaer'};
Object.getOwnPropertyDescriptor(obj, 'name').enumerable; // true
obj.propertyIsEnumerable('name'); // true
// Set attribute name to non-enumerable
Object.defineProperty(obj, 'name', {enumerable: false});
obj.propertyIsEnumerable('name'); // false
for(let i in obj){
    console.info(obj[i]); // 'ecmaer' is not traversed
}
Copy the code

Three Javascript ways to determine the type of a value

typeOf()

Typeof can be used to detect data types: note that TypeOF cannot 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
// When 'null', 'Array', and the usual 'object' are encountered, object is returned
typeof null // object
typeof [] Object (array.isarray (arr))
typeof {} // object
// When the new keyword is used and the wrapped Object is used, the 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 is used to check 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 is complex, using typeof will return object string, to distinguish between objects, arrays, functions, and simply using Typeof is not enough, want 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, difference and similarity of call, apply and bind

call

Call the executing function directly, binding the scope inside the function to the specified scope at execution time. (The call() method accepts a list of several arguments.)

const arr = [2.5.4.7.6]
const a = Function.prototype.call.apply(Math.max, arr)
console.log(a)  / / 7

// If the second argument to apply is null, -infinity is returned
const b = Function.prototype.call.apply(Math.max, null, arr)
console.log(b)  // -Infinity
Copy the code

bind

Creates a reference to a new function that is bound to a scope-specific scope and supports parameter passing. Bind is similar to call, except that call and apply immediately call functions. Bind simply binds this format:

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
const arr = [2.5.4.7.6]
const a = Function.prototype.call.apply(Math.max, arr)
console.log(a)  / / 7

// If the second argument to apply is null, -infinity is returned
const b = Function.prototype.call.apply(Math.max, null, arr)
console.log(b)  // -Infinity
Copy the code
The similarity
  • Both are used to change the function’s this object;
  • The first argument is the object to which this refers;
  • Can use the subsequent parameters to transmit parameters;
The difference between
  • ThisObj can be used to call a method instead of another object, changing the object context of a function from the original context to the new object specified by thisObj;
  • Bind () returns a new function to be called later, while apply() and call() are called immediately.
  • The only difference between call() and apply() is that the arguments are different. Call () is the syntactic sugar of apply();
Choose to use
  • If you don’t care how many arguments are passed to the function, use apply();
  • To determine how many arguments a function can take, and to express the relationship between parameters and arguments at a glance, use call();
  • If you want to call the method in the future and don’t need the function to return the result immediately, use bind();

The use of the Date object

First we need to define a variable:

const date = new Date();

You can then use the usual Date object methods directly.

  • Date(): returns the Date and time of the day;
  • Date(): returns the Date and time of the day;
  • GetDate (): returns a day in a month from the Date object (1 ~ 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 the year as four digits from the Date object;
  • GetYear () : 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 time from January 1, 1970 to the present;
  • GetTimezoneOffset (): Returns the minute difference between the local time and Greenwich Mean Time (GMT).
  • GetUTCDate (): returns the day of the month (1-31) from the Date object based on world time;
  • GetUTCDay (): returns the day of the week (1 ~ 6) from the Date object based on world time;
  • GetUTCMonth (): returns the month (0 to 11) from the Date object based on world time;
  • GetUTCFullYear (): returns a four-digit year from the Date object according to world time;
  • GetUTCHours (): returns the hour (0 ~ 23) of the object from the Date object according to the world time;
  • GetUTCMinutes (): the number of minutes (0 ~ 59) to return an object from a Date object according to world time;
  • GetUTCSeconds (): the number of seconds (0 to 59) in which an object is returned from a Date object based on world time;
  • GetUTCMillseconds (): the milliseconds (0 to 999) of the object returned from the Date object according to world time;
  • Parse (): Returns the number of milliseconds from midnight on January 1, 1970 to the specified date (string);
  • SetDate (): sets the Date of the month (1 ~ 31) in the Date object.
  • SetMonth (): Sets the month (0 to 11) in the Date object.
  • SetFullYear (): Sets the year (four digits) in the Date object;

Math.xx method

  • Math.ceil(): Logarithm rounding (ceiling function) is greater than or equal to x and is the nearest integer to it.
  • Math.floor(): Logarithmically round down (floor function).
  • Math.max(x,y): Returns the maximum value of 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.
  • Math.abs(x): Returns the absolute value of the number.
  • Math.acos(x): Returns the inverse cosine of the number.
  • Math.asin(x): Returns the arcsine of the number.
  • Math.atan(x): Returns the arctangent value 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): The natural logarithm (base e) of the number returned.
  • Math.sin(x): Returns the sine of a 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.

Simple array de-duplication

There are several ways to de-duplicate an array:

[…new Set(arr)] **

const arr = [4.5.3.4.6.5.8.6];
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 = [4.5.3.4.6.5.8.6];
const a = arr.reduce((prev,cur) = > prev.includes(cur) ? prev : [...prev,cur],[]);
console.log(a) // [4, 5, 3, 6, 8]
Copy the code

Filter is used to remove weight

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

HasOwnProperty is used for de-weighting

const arr = [4.5.3.4.6.5.8.6];
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