Common apis for JavaScript

Recently when doing the project often use some array, string API, some use is not very handy, remember before the web front-end development public number to see an API summary, feel very useful! Here are some of the apis I think are more commonly used for future reference

a. Array

1. new Set()

Array to heavy

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]
/ / or
const a = [...new Set(arr)]/ / recommend
Copy the code

[…] “Is used to iterate over the properties available to the currently used object and put the properties into the current object, often used in development.

2. sort()

Sort array elements (changing the array)

const arr = [1.2.3.4.5.6];console.log(arr.sort((a,b) = >a-b)) 
// [1,2,3,4,5,6
cosole.log(arr.sort((a,b) = >b-a))
// [6,5,4,3,2,1
'b' > 'a' => true
Copy the code

3. 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

5. shift()

Removes the first element from the array and returns the value of the first element.

const arr = [0.1.2];
const a = arr.shift(); / / 0
console.log(arr); / / [1, 2]
Copy the code

6. unshift()

Add one or more elements to the beginning of the array and return the new length (changing the 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

7. push()

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

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

8. 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

9. join()

Returns all arguments as a string (comma separated 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

10. slice(start, end)

Used to extract part of the original array, returns an extracted new array (deep copy), unchanged (strings apply, end not included).

/ / 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

11. 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. (Change the original array)

Splice (t, v, s) t: the starting position of the deleted element; 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

12. map()

Iterate over the members of the array, returning a new array based on the result. (Does not change the original 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

13. 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(item,index,arr){console.log(value)}))  
//3
Copy the code

14. 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
for (var v of arr) {
     console.log(a);  
}// 3 4 4 5
Copy the code

15. 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

16. some()& every()

These methods are similar to assert, which is used to determine whether an array member meets a condition.

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

some

The some method returns true as long as one of the array members returns true, false otherwise;

every

The every method returns true only if each value is true, otherwise false.

17. reduce()

Process each member of the array in turn, eventually accumulating a value.

Format:

reduce(() = > (pre, cur, curIndex, arr), initialValue)
Copy the code

Pre: mandatory, accumulative variable. Cur: mandatory, current variable; CurIndex: Optional, current position; Arr: Optional, primitive array; InitialValue: the initialValue passed to the function.

18. 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
const string = 'asdfghj';
console.log(string.indexOf('a')) / / 0
lastIndexOf()
Copy the code

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

19. 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

20. 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

21. 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 = arr.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 = arr.find(item= > item == 0);
console.log(b); //undefined(undefined if there is no qualified element)
Copy the code

b. String

1. 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

2. replace()

Replaces the matching string.

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

Extracts a specified character from an entry in the string.

const str = 'AA_BB_CC.bin';
console.log(str.replace(/[^\_]/g),' ')  // __(two underscores)
Copy the code

3. 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
const string = '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

4. 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

5. 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

6. 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

7. 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

8. 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

9. .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

a. 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

b. 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

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); // trueconsole.log(auto instanceof Object); // true
Copy the code