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 string arr.push(6); // insert a new element at the end of the array arr.push(6,7,8); // insert new elements at the end of the array a=arr.push(6,7,8); // Return the new length of the array console.log(arr) by adding it to the tail element; 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); // Insert a new element at the head of the array arr.unshift(-3,-2,-1,0); Var a=arr.unshift(-3,-2,-1,0); // Return 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 (); Var a=arr.pop(); //pop removes the last element of the array and returns the deleted element to 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. The shift (); Var a=arr.shift(); // Delete 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); Console. log(arr2); console.log(arr2); console.log(arr2); var arr3=arr.concat(0,-1,-2); Console. log(arr3) var arr4=arr.concat(0,arr1,["A","B"]); Console. log(arr4) var arr5=arr.concat(); Console. log(arr5) 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]; Var STR =arr.join(); // Merge arrays into strings, using commas by default, and connect 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, will concatenate the array elements end to end into the 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 console.log(arr1) with no arguments; Var arr1=arr.splice(0); var arr1=arr.splice(0); // Move all data to a 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); Arr1 var arr1=arr.splice(-2); Var arr1=arr.splice(0,1,-1); var arr1=arr.splice(0,1,-1); Var arr1=arr.splice(-1,1,0); var arr1=arr.splice(-1,1,0); Var arr1=arr.splice(2,2,10,11); var arr1=arr.splice(2,2,10,11); // 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); // Insert an element in the second part of the array -1 console.log(arr); Arr. Splice (2, 0, 1, 2, 3, 4); // Insert multiple elements console.log(arr) in the second part of the array;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); Var arr1=arr.slice(); // Copy array arr var arr1=arr.slice(0); Var arr1=arr.slice(3); Var arr1=arr.slice(-2); Var 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}); Console. log(index); 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); // Only the first 3 (subscript 1) console.log(index) can be queried; Var index = arr. IndexOf (3, 2); // Only the second 3 (subscript 4) is 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; While (true){index= arr.indexof (3,index); while(true){index= arr.indexof (3,index); console.log(index); if(index===-1) break; // select * from index++; // select * from 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"); Divs.pop (); // Get the HTML element whose tag name is div; Var arr= array. from(divs); / / the ES6 method and the divs this list, into an Array / / 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); For (var I =0; i<arr.length; Arr [I]. Onclick =clickHandler; } function clickHandler(){ console.log(this); var index=arr.indexOf(this); console.log(index); // If you click on the element in the list}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"; return item+10; });});}); console.log(arr2);Copy the code
Var arr=[1,3,5,7,2,4,6,8]; 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){ return a-b; // 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){console.log(a.charcodeat (0), b.charcodeat (0)); // str.charcodeat (0) => Convert the 0th item of STR string to Unicode 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){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){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. The 0th pass (starting with 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){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); ES6 console.log(array.isarray (arr)); 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,7,8,3,1,9,6,0,3,2 (4) the console. The log (c)Copy the code
2) Maximum math.max ()
C = Math. Max,7,8,3,1,9,6,0,3,2 (4) the console. The log (c)Copy the code
5, Random number math.random
c=Math.random()*10+1; // 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 Unicode encoding to 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 equivalent to 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, the name: "computer", price: 4999}, {id: 1002, the name: "motor", price: 1999}, {id: 1003, the name: "notepad", price: 9}, {id: 1004, the name: "textbook", price: 99}, {id: 1005, the name: "calculator", price: 149},]; 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); Var s=str.substring(4,2); var s=str.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); // Start with the subscript number and intercept the length 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(""); / / linking the console. The 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 year date.getYear(); Date.getmonth ()+1; date.getMonth()+1; // Get month from 0 date.getDate(); // Get the date date.getday (); // Get week from 0 0 is Sunday 1 is Sunday 1 date.gethours (); // Get the hour date.getminutes (); Date.getseconds (); // get date.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); SetHours (date.gethours () + 2); // Set it to 2 hours after the present date.getutcfullyear (); // Any time with UTC is GMT date.tostring (); // Convert directly to the string date.tolocaleString (); // Convert to local (Windows) format time string date.toutcString (); // Convert to the Greenwich 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