preface

Common built-in objects and methods include Array, Math, String, and date object methods.

Array Array objects

Push () adds one or more elements to the end of the array and returns the new length of the array

Arr = [1, 2, 3]      arr.push("a"."b"); // Insert stringarr.push(6); // Insert a new element at the end of the arrayArr. Push (June); // Insert multiple new elements at the end of the arrayA = arr. Push (June); // Returns the new length of the array by adding it to the tail element console.log(arr);  console.log(a); Copy the code

Returns the new length of the array

Unshift () adds one or more elements to the array header and returns the new array length

Arr = [1, 2, 3]arr.unshift(0); // Inserts a new element at the head of the arrayArr. Unshift (3, 2, 1, 0). // Insert multiple new elements in the header of the arrayVar a = arr. Unshift (3, 2, 1, 0). // Returns the new length of the array      console.log(arr);
 console.log(a); Copy the code

Returns the new length of the array

Pop () removes the last element at the end of the array and returns the deleted element

Arr = [6]arr.pop(); //pop has no arguments. Remove the last element of the arrayvar a=arr.pop(); //pop removes the last element of the array and returns the deleted element      console.log(arr);
      console.log(a);
Copy the code

Return the deleted element

Shift () removes the first element of the array and returns the deleted element

Arr = [6]arr.shift(); // Delete the first element of the arrayvar a=arr.shift(); // Remove the first element of the array, and return the deleted element      console.log(arr);
      console.log(a);
Copy the code

Returns the deleted element

Deleting or adding changes the length of the array

5, concat() array merge, return a new array, the original two arrays are not changed

Var arr = [1, 2, 3, 4];Var arr1 =,6,7,8 [5];var arr2=arr.concat(arr1); // Array merge, return a new array, the original two arrays do not change      console.log(arr2);
var arr3=arr.concat(0,-1,-2); // An array can merge elements as well as arrays. Multiple elements are merged with the original array console.log(arr3)  var arr4=arr.concat(0,arr1,["A"."B"]); // concat can merge both elements and arrays console.log(arr4) var arr5=arr.concat(); // If you use concat directly, you can copy arrays console.log(arr5) Copy the code

6. Join () returns each element of the array as a new string concatenated with the specified character

Var arr = [1, 2, 3, 4, 5]; // join returns each element of an array as a new string with the specified concatenation of charactersvar str=arr.join( ); // Merge arrays into strings, using commas by default, concatenated      console.log(str);
      var str=arr.join("|"); // In this case, the join argument is the string concatenation v      console.log(str);
 var str=arr.join(""); // ""As a concatenator, it concatenates the elements of an array into a string console.log(str); Copy the code

7. Splice () this method removes a given number of elements from a specified location, inserts the desired elements at that location, and returns a new array of the deleted elements

Splice (where to start, how many elements to delete, elements to insert);

1) splice deletes all array return values

var arr1=arr.splice(); // Returns an empty array without any arguments      console.log(arr1);
The first argument is 0, which indicates the number of bytes from the 0th bit, and the second argument is not filled in, which means to the endvar arr1=arr.splice(0); // Move all data to the new array      console.log(arr1);
Copy the code

2) Splice can be used from front to back or from back to front

Var arr1 = arr. Splice (0, 3); // Remove 3 elements from bit 0 and return to arr1var arr1=arr.splice(-2); // The number of digits can be negative, and the number of digits can be negative, and the number of digits to delete is backwardVar arr1 = arr. Splice (0, 1, 1); // Starting at bit 0, delete 1 element, and insert element -1 at that position, replaceVar arr1 = arr. Splice (1, 0). // The last substitution bit of the array is 0Var arr1 = arr. Splice,2,10,11 (2); // replace the first two elements of the array with 10,11Copy the code

3) Splice can insert one or more elements

Var arr = [1, 2, 3, 4, 5];Arr. Splice (2, 0, 1); // Inserts an element -1 in the second part of the array      console.log(arr);
Arr. Splice (2, 0, 1, 2, 3, 4); // Insert multiple elements in the second part of the array      console.log(arr);
Copy the code

8. Slice (start,end) intercepts the contents of the copied array at the specified location and returns the new array without changing the original array

Starting with the subscript start, intercepts to end, including start but not end. The second parameter is not written, and is truncated to the tail by default, only from front to back

Var arr1 = arr. Slice (1, 4); // start with the first bit and end with the fourth bitvar arr1=arr.slice(); // Copy the array arrvar arr1=arr.slice(0); // Copy the arrayvar arr1=arr.slice(3); // copy from the third bit to the tailvar arr1=arr.slice(-2); // Start from the last second to the endvar arr1=arr.slice(-3,-1); // From third to lastCopy the code

9, The indexOf position is the subindex

If the index of the element is not found, -1 is returned. If the index of the element is not found, -1 is returned

1) Objects cannot be queried

      var arr=[{a:1},{a:2},{a:3},{a:4}];
var index=arr.indexOf({a:1}); // This is a new object with a different address      console.log(index);
Copy the code

If no query is found, -1 is returned

2) Query all the same elements

Var arr =,3,1,2,3,5,2,3,4,6 [1];var index=arr.indexOf(3); // Select * from 1;      console.log(index);
Var index = arr. IndexOf (3, 2); // Only the second 3 can be queried (subscript 4)      console.log(index);
Copy the code

Query all the same elements using a circular query

Var arr =,3,1,2,3,5,2,3,4,6 [1];var index=0; // Use a loop to find all elements in the array with a value of 3 and print the subscript      while(true) {           index=arr.indexOf(3,index);
           console.log(index);
 if(index===-1) break; If the value is -1, no further query is performed index++;  } Copy the code

10, Array.from(array-like list) to Array

1) Obtain the tag list according to the tag name (obtain the tag list, not array, can not directly use the array method

      var divs=document.getElementsByTagName("div"); // Get the HTML element whose tag name is div
Divs. Pop (); // Error, cannot use array method directly instead of array
var arr=Array.from(divs); Divs = divs; divs = divs/ / ES5 writing = > var arr = Array. The prototype. Slice. Call (divs);Copy the code

2) Add click events to all div elements

      var divs=document.getElementsByTagName("div");
var arr=Array.from(divs); // Convert all divs into arrays
      for(var i=0; i<arr.length; I++){// iterate over the number group to add click events to each div          arr[i].onclick=clickHandler;
 }  function clickHandler() { console.log(this);  var index=arr.indexOf(this); console.log(index); // To determine which element in the list is clicked } Copy the code

11, The lastIndexOf(where to start the search) searches from back to front

Var arr =,3,1,2,3,5,2,3,4,6 [1];      var index=arr.lastIndexOf(3);
console.log(index); // Print the subscript 7Copy the code

Traversal groups (forEach and Map)

1) forEach

Arr. ForEach (function(element in array, subscript of each element, array itself){})

Var arr =,2,3,5,6,7,8,9 [1];      arr.forEach(function(a,b,c){
         console.log(a,b,c);
      })
Copy the code

ForEach does not return a value

2) Map returns a new array of the same length as the original array

arr.map(function(item,index,arr){ })

Var arr =,5,7,9,1,2,4 [3];      var arr2=arr.map(function(item,index,arr){
            // console.log(item,index,arr);
            // return "a";
            returnitem+10; // Use in mapreturnAdd the corresponding data to the corresponding subscript });  console.log(arr2); Copy the code

// Create a new array for elements greater than 4 (undefined)Var arr =,3,5,7,2,4,6,8 [1];      var arr1=arr.map(function(item){
            if(item>4){
                return item;
 }  });  console.log(arr1); Copy the code

Map returns a value, a new array of the same length as the original array, and the contents of the elements are determined by return

13, arr.sort() sort only numbers up to 10

Cons: Sort by character sort(function(last, last){}) only applies to numeric values

1) Numerical sorting

Var arr =,3,5,7,2,4,6,8 [1];      arr.sort(function(a,b){      
           returna-b; // From small to big           // return  b-a; // From large to small        })    
 console.log(arr); Copy the code

2) Character sorting, first convert characters to Unicode encoding

      var arr=["n"."c"."g"."h"."a"."j"."y"."k"];
      arr.sort(function(a,b){// Sort the charactersconsole.log(a.charCodeAt(0),b.charCodeAt(0)); // str.charcodeat (0) => Converts the 0th entry of the STR string to Unicode encoding           return a.charCodeAt(0)-b.charCodeAt(0);  // a-z
           // return b.charCodeAt(0)-a.charCodeAt(0);  // z-a
 })  console.log(arr); Copy the code

14, some ()

Checks if there are elements in the array that meet the criteria, returning true if there are, false if there are none

If there is one element that meets the condition, it will return true

Var arr =,4,6,2,7,9,0 [1];        var bool=arr.some(function(item,index,arr){// Go through the list to see if there is an element greater than 5           return item>5;
        });
        console.log(bool);
Copy the code

15, every ()

var bool=arr.every(function(item,index,arr){ }); Check whether all elements in the array meet the criteria. If one element does not meet the criteria, jump directly. If all elements meet the criteria, return true

Var arr =,4,6,2,7,9,0 [1];        var bool=arr.every(function(item,index,arr){// Check whether all elements in the array are greater than 2            return item>2;
        });
        console.log(bool); 
Copy the code

16, the filter ()

The requirement is to return anything in the array greater than 5 to a new array

The first thing that comes to mind is a map, which only makes the original array and the new array the same length

        var arr1=arr.filter(function(item,index,arr){
           return item>5;
        });
        console.log(arr1);
Copy the code

17, the reduce ()

The first bit of the array is traversed, the 0th bit is not traversed, and the subscript starts at 1

So value is the 0th entry in the array, and then every value is undefined

If you use return in a function, you assign the return value to a value in the loop

Var arr =,3,4,7,3,5,8,9 [10];        arr.reduce(function(value,item,index,arr){
// The number of loops is the number of arrays -1// value is the last iterationreturn, the 0th pass (starts as the 0th entry of the array)            console.log(value);
 return value+1  }) Copy the code

Cumulative summation of array elements

Reduce returns a value that is iterated until the last return

Var arr =,3,4,7,3,5,8,9 [10];        var sum=arr.reduce(function(value,item){
            return value+item;
        });
        console.log(sum);
Copy the code

You want to sum the elements of a cumulative additive array, given the cardinality 100, which is the initial value

Var arr =,3,4,7,3,5,8,9 [10];        var sum=arr.reduce(function(value,item){
// The argument after the function is the initial value of the sum            console.log(value);
            return value+item;
}, 100);Copy the code

18, Array. IsArray ()

To check if it’s an array

Var arr = [1, 2, 3, 4];        var obj={a:1};
        console.log(typeof arr);
// Check if the element is an arraytrueOtherwise returnsfalseThe ES6        console.log(Array.isArray(arr));
 console.log(Array.isArray(obj)); Copy the code

2. Math method

1. PI and the square root of 2

Math.PI; / / ΠMath.SQRT2; // The square root of 2 constant can only be used and cannot be modifiedCopy the code

2, rounded up

1) Integer math.floor ()

A = Math. Floor (25.6);      console.log(a);
Copy the code

2) Round up math.ceil ()

B = math.h ceil (25.6);      console.log(b);
Copy the code

3, Round math.round ()

Error in method

C = Math. Round (25.5);      console.log(c);
Copy the code

The rounding of negative numbers is generally converted to a positive number

4. Maximum and minimum values

1) Minimum math.min ()

C = Math. Min (4,7,8,3,1,9,6,0,3,2)      console.log(c)
Copy the code

2) Maximum math.max ()

C = Math. Max (4,7,8,3,1,9,6,0,3,2)      console.log(c)
Copy the code

5, Random number math.random

c=Math.random()*10+1; // A random number between 1 and 10      console.log(c)
Copy the code

Random numbers that are not integers are generally rounded

      c=Math.random()*10+1;
console.log(Math.floor(c)); // round downCopy the code

6. Other methods


String String method

1, the charAt ()

Gets the character of the subscript position, and STR [1]; The same

      var str="abcdef";
      console.log(str.charAt(3));
Copy the code

2, charCodeAt ()

Converts characters at subscript positions to Unicode encoding

      var str="abcdef";
      console.log(str.charCodeAt(2));
Copy the code

3, String. FromCharCode ()

Converts Unicode encoding to a string

n=String.fromCharCode(65); // Convert the Unicode encoding to a string      console.log(n);
Copy the code

4, STR. Concat ()

Concatenation string, effect equivalent to concatenation +

        var str="abc";
        var str1="def";
var str2=str.concat(str1); // var str2=str+str1; This is the same as concat        console.log(str2); 
Copy the code

5、 indexOf() 、lastIndexOf()

The indexOf the search character is the same as the indexOf the array

      var arr=[
        {id:1001,name:"Computer",price:4999},
        {id:1002,name:"Motor",price:1999},
        {id:1003,name:"Notepad",price:9},
        {id:1004,name:"Book",price:99},
 {id:1005,name:"Calculator",price:149},  ];  // fuzzy search var arr1=arr.filter(function(item){  return item.name.indexOf("This") > 1 });  console.log(arr1); Copy the code

6, the replace ()

Replace, like splice() in arrays;

Replace does not modify the content of the original character, and returns a new modified string

If two identical elements appear, only the element found the first time is modified

      var str="abcdecf";
      var str1=str.replace("c"."z");
      str.replace()
      console.log(str,str1);
Copy the code

7, slice (start, end)

Slice (starting at and ending before the subscript) intercepting copy strings are allowed to have negative values, which indicate backwards to forwards

      var str="abcdecf";
Var s = STR. Slice (1, 2);      console.log(s);
Copy the code

8, the substring ()

      var str="abcdecf";
Var s = STR. The substring (2, 4); // Similar to slice// Substring does not allow negative numbers. All negative numbers are before 0, so negative numbers are 0// You can intercept assignments backwardsVar s = STR. The substring (4, 2); console.log(s); Copy the code

9, substr (start with subscript, truncate length);

      var str="abcdecf";
Var s = STR. Substr (- 2, 5); // Cut the length from the index      console.log(s);
Copy the code

Split converts a string into an array using a separator

      var str="a,b,c,d,e,f";
      var arr=str.split(",");
      console.log(arr);
Copy the code

11, reverse (); Array elements in reverse order or reverse order, this is an array method

      var str="abcdefg";
      var str1=str.split("").reverse().join(""); / / :      console.log(str1)
Copy the code

12, string conversion case

1) change str.toLowerCase toLowerCase

      console.log("ABC".toLowerCase()); // Convert the string to lowercaseCopy the code

2) STR. ToUpperCase is uppercase

      console.log("abc".toUpperCase()); // Convert the string to uppercaseCopy the code

Date object

Create a date object

var date=new Date(); // Create a date objectCopy the code

2. Get the date

      var date=new Date(); 
date.getFullYear(); // Get the yeardate.getYear(); // Get the year from 1900, there is a problemdate.getMonth()+1; // Get months from 0date.getDate(); // Get the datedate.getDay(); // Get week from 0, 0 is Sunday, 1 is Sundaydate.getHours(); // Get the hourdate.getMinutes(); // Get minutesdate.getSeconds(); / / for secondsThe date. The getMilliseconds (); // Get milliseconds console.log(date); Copy the code

2. All the above dates can be set

      var date=new Date(); 
      date.setFullYear(2021);
date.setMonth(12); // In January, the year +1 is rounded from 0;date.setDate(40); // Set the carrydate.setHours(date.getHours() + 2); // Set it to 2 hours after the present timedate.getUTCFullYear(); // All time with UTC is Greenwich mean timedate.toString(); // Convert directly to a stringdate.toLocaleString(); // Convert to a local (Windows) format time stringdate.toUTCString(); // Converts to a Greenwich mean time string console.log(date); Copy the code

3. Timestamp

date.getTime(); // The number of milliseconds from 00:00:00 on January 1, 1970 to the presentCopy the code

As time goes by, this number will keep getting bigger and bigger, getting different values every millisecond, so this number will never be repeated

The browser thinks that if the address is the same each time, it checks the browser cache first and uses the local cache if it does

You can timestamp each visit to a different address to avoid local caching by the browser

This article is formatted using MDNICE