Built-in objects
Built-in objects refer to some objects in THE JS language, which are used by developers and provide some common or basic and necessary functions (attributes and methods).
JS objects fall into three categories:
- Custom objects: belong to ECMAScript
- Built-in objects: belong to ECMAScript,
Math
,Date
,Array
,String
. - Browser object: JS unique, JS API learning
The Math object
The Math object
Math is not a constructor and does not need to be called by new; it uses properties and methods inside. MDN Math document
Example: Encapsulate the Math object
var myMath = {
PI:2.141592653.max:function(){
var max=arguments[0];
for (var i=1; i<=arguments.length; i++){if(arguments[i]>max){
max=arguments[i]; }}returnmax; }}Copy the code
Math uses built-in properties and methods
Properties/methods | describe |
---|---|
Math.PI | PI |
Math.floor() | Take down the whole |
Math.ceil() | Take up the whole |
Math.round() | Round, other numbers are rounded, only 5 is taken to the larger -1.1→-1 -1.5→-1 |
Math.abs() | The absolute value |
Math.max()/Math.min() | Find the maximum and minimum |
Math.random() | Return a random decimal [0,1] |
I get a random integer between two numbers
This example returns a random integer between the specified values. This value is not less than min (or an integer up if min is not an integer) and is less than (not equal to) Max.
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; // No maximum value, no minimum value
}
Copy the code
Get a random integer between two numbers, including two numbers
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; // Contain maximum value, contain minimum value
}
Copy the code
The date object
The Date() object is a constructor that must be called with new to create our Date object, which needs to be instantiated before it can be used.
- If no arguments are entered, the Date constructor creates a Date object based on the current time set by the system.
var arr = new Array(a);var obj = new Object(a);var date = new Date(a);var date1 = new Date(2019.10.1);
console.log(date1);// Return November instead of October
var date2 = new Date('the 2019-10-1 8:8:8');
console.log(date2);// The return is correct
// Tue Oct 2019 08:08:08 GMT+0800
Copy the code
Date formatting
The method name | instructions |
---|---|
getFullyear() | To obtain the |
getMonth() | To get the current month from 0 to 11, +1 is required |
getDate() | Get the current date |
getDay() | Get day of the week Sunday 0 to Saturday 6 |
getHours() | Get the current hour |
getMinutes() | Get current minute |
getSeconds | Get the current second |
// Encapsulates a function that returns the current time
function getTime() {
var time = new Date(a);var h = time.getHours();
h = h < 10 ? '0' + h : h;
var m = time.getMinutes();
m = m < 10 ? '0' + m : m;
var s = time.getSeconds();
s = s < 10 ? '0' + s : s;
return h + ':' + m + ':' + s;
}
console.log(getTime())
Copy the code
Four methods to obtain the total number of milliseconds of Dtae (timestamp)
- The Date object is based on the number of milliseconds from January 1, 1970.
//1.valueOf getTime
var time = new Date(a);console.log(date.valueOf());
console.log(date.getTime());
//2.
var date1 = +new Date(a);console.log(date1);
//3. H5 additions get the total number of milliseconds
console.log(Date.now());
Copy the code
Case study: Countdown
function countDown(time) {
var nowTime = +new Date(a);// Total milliseconds of the current time
var inputTime +new Date(time);// User input time total good description
var times = (inputTime - nowTime); / / 1000
var d = parseInt(times / 60 / 60 / 24);
var h = parseInt(times / 60 / 60 % 24);
var m = parseInt(times / 60 % 60);
var s = parseInt(times % 60);
return d + 'day' + h + 'when' + m + 'points' + s + '秒';
}
Copy the code
The array object
Juejin. Cn/post / 700776…
String object
Basic packing type
For ease of operation, JS provides three special reference types: String, Number, and BOOlean. A primitive wrapper type is one that wraps a simple data type into a complex data type, so that the primitive data type has properties and methods.
The following code can be executed:
var str = 'andy';
console.log(str.length);
Copy the code
Even though strings are simple data types, we can still use the attribute length. Why is that? Because JS wraps string types as complex data types:
//1. Generate temporary variables to wrap simple types into complex data types
var temp = new String('andy');
//2. Assign to the character variable we declared
str = temp;
//3. Destroy temporary variables
temp = null;
Copy the code
Immutable string
The value inside the string is immutable, although it looks like it can change the content, but in fact the address is changed, and a new memory space is created in memory.
var str = 'abc';
str = 'hello';
// When STR is reassigned, the constant 'ABC' is not modified and remains in memory.
// Since strings are immutable, there are efficiency problems when concatenating large numbers of strings:
var str = ' ';
for(var i = 0; i < 100000; i++){ str += i; }console.log(str);// This result takes a lot of time to display because new space is constantly being created
// So don't reassign or concatenate strings too much
Copy the code
Commonly used method
All string methods do not modify the string itself and return a new string after the operation.
The method name | instructions |
---|---|
IndexOf (‘ Character to find ‘,[starting position]) | Returns the position of the specified content in the meta-string, or -1 if it cannot be found |
lastIndexOf() | Go back to front. Just look for the first match |
Find the position and number of occurrences of a character
var str = "ofsjhfofsddfofsodfdofdsfoofd";
var idnex = str.indexOf('o');
var num = 0;
while(index ! = = -1) {
console.log(index);
num ++;
index = str.indexOf('o',index+1);
}
Copy the code
Return character by position (emphasis)
The method name | instructions |
---|---|
charAt(index) | Returns the character at the specified position |
charCodeAt(index) | Gets the ASCll code at the specified location |
str[index] | Get the character at the specified position HTML5, IE8+ support and charAt() equivalent |
//1.charAt(index)
var str = 'andy';
console.log(str.charAt(3));
for (var i = 0; i < str.length; i++) {
console.log(str.charAt(i));
}
//2.charCodeAt(index)
console.log(str.charCodeAt(0));//97 Purpose: Determine which key the user presses
//3. str[index]
console.log(str[0]);//a
Copy the code
Determine the most characters in a string and count the number of occurrences.
var str = 'afkdofeooofdjfsa';
var o = {};
for (var i = 0; i < str.length; i++) {
var chars = str.charAt(i);
if (o[chars]) {
o[chars]++;
} else {
o[chars] = 1; }}console.log(o);
var max = 0;
var ch = ' ';// Which character occurs the most times in the global variable
for (var k in o) {
if(o[k] > max) { max = o[k]; ch = k; }}console.log(max);// The maximum number of occurrences
console.log(ch)
Copy the code
The method name | instructions |
---|---|
Replace (‘ replaced character ‘,’ replaced character ‘) | Only the first character is replaced |
Split (‘ separator ‘) | Characters are converted to arrays |
Put all of the values in a stringo
Replace with*
var str1 = 'r4jfroffopfdoofdofsd';
while (str1.indexOf('o')! = =1) {
str1 = str1.replace('o'.The '*');
}
Copy the code
Convert strings to arrays
var str = 'red, pink, blue';
console.log(str.split(', '));
var str1 = 'red&pink&blue';
console.log(str2.split('&'));
Copy the code
reference
Developer.mozilla.org/zh-CN/docs/…