JavaScript built-in object

1 Math object

Math objects are used to perform math related operations on numbers. Instead of instantiating objects, you can directly use their static properties and methods. The common properties and methods of math objects are shown in the following table.

memberfunction
PIObtain the PI and the result is 3.141592653589793
abs(x)Gets the absolute value of x, which can be passed in a normal value or a value represented by a string
max()Gets the maximum value of all parameters
min()Gets the minimum value of all parameters
pow(base, exponent)Gets the exponent power of the base, that is, the base exponent
sqrt(x)Get the square root of x
ceil(x)Gets the smallest integer greater than or equal to x, rounded up
floor(x)Gets the largest integer less than or equal to x, rounded down
round(x)Gets the rounded integer value of x
random()Gets a random value greater than or equal to 0.0 and less than 1.0

max() and min() examples:

console.log(Math.max(1, 2, 3, 4, 5));//Maximum output
console.log(Math.min(1, 2, 3, 4, 5));//Output minimum

The result is:
5
1

pow(base, exponent) and sqrt() instances:

console.log(Math.pow(2, 3))//Find the third power of 2, 8
console.log(Math.sqrt(4))//Root 4, 2

The result is: 8 2

ceil() and floor() instances:

var m = 3.67;
console.log(Math.ceil(m));//Get the smallest integer greater than or equal to m, 4
console.log(Math.floor(m));//Gets the maximum integer less than or equal to m, 3

The result is: 4 3

round() instance:

console.log(Math.round(3.45));//Rounded integer value

The result is: 3

random() instance: find a random integer between 0 and 10

var k = Math.round(Math.random() * 10);//Find a random integer between 0 and 10
console.log(k);

[case] the number guessing game is to randomly input a number to judge whether the number is the same as the automatically generated number. If the entered number is greater than the generated number, you will be prompted with "you guessed too big"; On the contrary, prompt "you guessed small". If the input number is the same as the generated number, prompt "guessed right" and end the code execution.

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}
var random = getRandom(1, 10);
while (true) {
    var num = prompt("Guess the number, in the range of 1-10 between");
    if (num > random) {
        alert("Guess it's too big");
    } else if (num < random) {
        alert("Guess it's small");
    } else {
        alert("Bingo");
        break;
    }
}

2 date object

The date object in JavaScript can only be used by instantiating the object with new Date(), which is the constructor of the date object.

The Date() constructor can pass in some parameters. The example code is as follows:

// Method 1: no parameters
var date1 = new Date();
// Method 2: input year, month, day, hour, minute and second (the range of month is 0 ~ 11)
var date2 = new Date(2021, 11, 19, 19, 46, 56);
// Method 3: use string to represent date and time
var date3 = new Date('2019-10-16 10:57:56');

Common get methods for date objects:

methodeffect
getFullYear()Get the 4-digit number representing the year, such as 2021
getMonth()Get the month, ranging from 0 to 11 (0 represents January, 1 represents February, and so on)
getDate()Get a day in the month, range 1 ~ 31
getDay()Get the week, ranging from 0 to 6 (0 represents Sunday, 1 represents Monday, and so on)
getHours()Get the number of hours and return 0 ~ 23
getMinutes()Get minutes, range 0 ~ 59
getSeconds()Gets the number of seconds, ranging from 0 to 59
getMilliseconds()Gets the number of milliseconds, ranging from 0 to 999
getTime()Gets the number of milliseconds from 1970-01-01 00:00:00 to the time represented by the Date object

Example:

var date1 = new Date();//Instantiate object
console.log("This year is" + date1.getFullYear() + "year");//Output year
console.log("This month is the third" + (date1.getMonth() + 1) + "month");//Output month
console.log("Today is the third day of this month" + date1.getDate() + "day");//Output the day of this month
console.log("Today is Sunday" + (date1.getDay()));//Output week
console.log("Now it is"+date1.getHours()+"Time");//Output hours
console.log("Now it is"+date1.getMinutes()+"branch");//Output minutes
console.log("Now it is"+date1.getSeconds()+"second");//Output seconds
console.log("Now it is"+date1.getMilliseconds()+"millisecond");//Output milliseconds
console.log(date1.getTime());//Outputs the number of milliseconds from 1970-01-01 00:00:00 to the time represented by the Date object


Common set methods for date objects:

methodeffect
setFullYear(value)Set Year
setMonth(value)Set month
setDate(value)Set a day in the month
setHours(value)Set hours
setMinutes(value)Set minutes
setSeconds(value)Set seconds
setMilliseconds(value)Set milliseconds
setTime(value)The time is set by the number of milliseconds timed from 1970-01-01 00:00:00

Other methods:

methodeffect
toJSON()Returns a JSON format string
toDateString()Convert date to character
toLocaleDateString()A string that converts a date to a local date format

Example:

var d = new Date();
console.log(d.toJSON());
console.log(d.toDateString());
console.log(d.toLocaleDateString());


[case] "fishing in three days and drying the net in two days"
Assuming 2008-08-08 is the first day to dry the net, is it fishing or drying the net today?

var d1 = new Date(2008 - 08 - 08);
var d2 = new Date();
var s = d2.getTime() - d1.getTime();//Get the number of milliseconds today from August 8, 2008
var m = parseInt(s / 1000 / 3600 / 24);//Get the number of days from today to August 8, 2008
switch (m % 5) {
    case 0://Day 0 is the first day of fishing
    case 1: console.log("Fishing today"); break;
    case 2:
    case 3:
    case 4: console.log("Drying the net today"); break;
}

3 array object

3.1 array type detection

(1) Array type detection method:
There are two common methods for array type detection: using the instanceof operator and using the Array.isArray() method.

var arr = [];
var obj = {};
// Mode 1
console.log(arr instanceof Array);	// Output result: true
console.log(obj instanceof Array);	// Output result: false
// Mode 2
console.log(Array.isArray(arr));	// Output result: true
console.log(Array.isArray(obj));	// Output result: false

3.2 traversal of array

Assume that arr is an array:

1. Use for loop traversal

for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

2. Use for... in traversal

for (var i in arr) {
    console.log(arr[i]);
}

3. Use for... of traversal

for (var i of arr) {
    console.log(i);
}

4. Traversal using forEach

arr.forEach(function (t) {
    console.log(t);
})

5. Use map traversal

arr.map(function (t) {
    console.log(t);
})

3.3 adding or deleting array elements

JavaScript array objects provide methods to add or delete elements. You can add new array elements at the end or beginning of the array, or remove array elements at the end or beginning of the array. The method is as follows:

Method nameFunction descriptionReturn value
Push (parameter...)Adding one or more elements to the end of the array will modify the original arrayReturns the new length of the array
Unshift (parameter 1...)Adding one or more elements at the beginning of the array will modify the original arrayReturns the new length of the array
pop()Delete the last element of the array. If it is an empty array, it returns undefined, which will modify the original arrayReturns the value of the deleted element
shift()Delete the first element of the array. If it is an empty array, it returns undefined, which will modify the original arrayReturns the value of the first element

Example:

var arr = [2, 5, 7, 9, 3];
console.log(arr.push(1));//Add a number at the end of the array, and the return value is the length of the array
console.log(arr);//Output the array

The result is:
6
[ 2, 5, 7, 9, 3, 1 ]

var arr = [2, 5, 7, 9, 3];
console.log(arr.unshift(1));//Add a number at the beginning of the array, and the return value is the length of the array
console.log(arr);//Output the array

The result is:
6
[ 1, 2, 5, 7, 9, 3 ]

var arr = [2, 5, 7, 9, 3];
console.log(arr.pop());//Output and delete the last element of the array
console.log(arr);//Output the array

The result is:
3
[ 2, 5, 7, 9 ]

var arr = [2, 5, 7, 9, 3];
console.log(arr.shift());//Output and delete the first element of the array
console.log(arr);//Output the array

The result is:
2
[ 5, 7, 9, 3 ]

[case] filter array
It is required to eliminate the data with salary of 2000 or above in the array containing salary, and put the number less than 2000 back into the new array.

var arr = [1500, 1200, 2000, 2100, 1800];
var newArr = [];//Define a new array to store wages below 2000
for (var i = 0; i < arr.length; i++) {//Facilitate the array
    if (arr[i] < 2000) {//If you traverse to a number less than 2000
        newArr.push(arr[i]);//Add this number to the new array
    }
}
console.log(newArr);//Output new array

The result is: [1500, 1200, 1800]

3.4 array sorting

JavaScript array object provides array sorting methods, which can sort array elements or reverse the order of array elements. The sorting method is as follows:

methodFunction description
reverse()Invert the position of elements in the array. This method will change the original array and return the length of the new array. The default sort order is to convert elements into strings and then compare their UTF-16 code unit value sequences. Because it depends on the specific implementation, the time and space complexity of sorting cannot be guaranteed.
sort()Sort the elements of the array. This method will change the original array and return the length of the new array

example:

var arr = [4, 6, 8, 32, 2, 7, 9];
console.log(arr.sort());

The result is: [2, 32, 4, 6, 7, 8, 9]

var arr = [4, 6, 8, 32, 2, 7, 9];
console.log(arr.reverse());

The result is: [9, 7, 2, 32, 8, 6, 4]

3.5 array index

In development, to find the position of the specified element in the Array, you can use the retrieval method provided by the Array object. The retrieval method is as follows:

methodFunction description
indexOf()Returns the first index of the given value that can be found in the array, or - 1 if it does not exist
lastIndexOf()Returns the index of the last specified element in the array, or - 1 if it does not exist

Note: by default, the retrieval starts from the position of the specified array index, and the retrieval method is the same as the operator "= =", that is, the more successful results will be returned only when they are congruent.

Example:

var arr = [45, 67, 8, 23, 67, 9, 67];
console.log(arr.indexOf(67));//Returns the first index of the location of 67
console.log(arr.lastIndexOf(67));//Returns the last index of the location of 67

The results are: 1 6

[case] array to remove duplicate elements
Case requirements: it is required to remove duplicate elements in a set of data.

function unique(arr) {
    var newArr = [];//Set an empty array to store non duplicate numbers
    for (var i = 0; i < arr.length; i++) {//Traverses the passed in array
        if (newArr.indexOf(arr[i]) === -1) {//If there is no number traversed in the new array, the index is - 1
            newArr.push(arr[i]);//Add this number to the new array
        }
    }
    return newArr;//Returns a new array
}
var arr = [45, 67, 8, 23, 67, 9, 67];
console.log(unique(arr));

The result is: [45, 67, 8, 23, 9]

3.6 converting arrays to strings

In development, you can use the join() and toString() methods of array objects to convert arrays into strings. The method is as follows:

methodFunction description
toString()Convert the array to a string, separating each item with a comma
join('separator ')Concatenates all elements of an array into a string

Example:

// Use toString()
var arr = ['a', 'b', 'c'];
console.log(arr.toString());// Output results: a,b,c
// Use join()
console.log(arr.join());// Output results: a,b,c
console.log(arr.join(''));// Output result: abc
console.log(arr.join('-'));// Output result: a-b-c

The result is:
a,b,c
a,b,c
abc
a-b-c

3.7 other methods

JavaScript also provides many other common array methods. For example, fill array, connect array, intercept array elements, etc. The method is as follows:

methodFunction description
fill(value,start,end)Fills all elements within the specified subscript range in the array with a fixed value
splice()Array deletion. The parameter is split (starting from the number of items to be deleted), and returns a new array of deleted items
slice()Array interception. The parameter is slice(begin, end). It returns a new array of intercepted items
concat()Connect two or more arrays without affecting the original array and return a new array

Note: slice() and concat() methods return a new array after execution, which will not affect the original array. The remaining methods will affect the original array after execution.

Example:

var arr = [1, 2, 3, 4];
console.log(arr.fill(0, 2, 4));//Fill 0 from 2 to 4

The result is: [1, 2, 0, 0]

var arr = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(arr.splice(2, 4));//Delete the 4 numbers starting from the second (excluding 2)
console.log(arr);//Output array after deleting numbers

The result is:
[ 3, 4, 5, 6 ]
[ 1, 2, 7, 8 ]

var arr = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(arr.slice(2, 5));//Intercepts an array starting from 2 (excluding 2) to 5

The result is: [3, 4, 5]

var arr1 = [1, 2, 3, 4];
var arr2 = [9, 8, 7, 6];
console.log(arr1.concat(arr2));

The result is: [1, 2, 3, 4, 9, 8, 7, 6]

4 string object

4.1 use of string objects

1. Create directly

var Variable name = "character string";

2. Created by String object

var Variable name = new String("character string");

4.2 default attributes

String default attribute: length, used to record the length of the string. Usage:

String variable name.length

Example:

var str = new String("Orange cat is not fat");
console.log(str.length);

The result is 5

4.3 return position according to characters

String objects provide properties and methods for retrieving elements. The common properties and methods of string objects are as follows:

methodFunction description
indexOf(searchValue)Gets the position where searchValue first appears in the string. If - 1 is returned, it means value is not found
lastIndexOf(searchValue)Gets the last occurrence of searchValue in the string

Example:

var str = new String("Orange cat is not fat");
console.log(str.indexOf("no"));

The result is 3

var str = new String("Orange cat is not fat");
console.log(str.indexOf("No 1"));

The result is - 1

If the result is - 1, value is not found

var str = new String("Orange cat is not fat. Orange cat is not fat");
console.log(str.lastIndexOf("eat"));

The result is 7

[case] it is required to find the location and number of occurrences of all specified elements in a group of strings. The string is' Hello World, Hello JavaScript '.

var str = "Hello World!Hello JavaScript!";
var index = str.indexOf("o");//Find the location where o first appears
var num = 0;//Define a counter num as 0
while (index != -1) {
    console.log(index);//
    index = str.indexOf("o", index + 1);//Keep looking for the next o
    num++;
}
console.log("Number of occurrences", num);

4.4 return characters according to position

A string object provides a method for obtaining a character in a string. The method is as follows:

methodFunction description
charAt(index)Gets the character of the index position, which is calculated from 0
charCodeAt(index)Gets the ASCII code of the character at the index position
str[index]Get the character at the specified position (new in HTML5) in the form of object name, attribute name or object name [attribute name]

Common ASCII codes are as follows:

elementASCII code
048
a97
A65
Space32

Example:

var str = "Hello World!Hello JavaScript!";
console.log(str.charAt("9"));

The result is: l

var str = "Hello World!Hello JavaScript!";
console.log(str.charCodeAt(9))

108
[case] count the most characters and times

var str = "Apple";
var o = {};//Define an empty object
for (var i = 0; i < str.length; i++) {
    var chars = str.charAt(i);//Get the character at i position and assign it to chars
    if (o[chars]) {//Indicates that chars exist in object o
        o[chars]++;
    } else {
        o[chars] = 1;
    }
}
console.log(o);

The result is: {A: 1, p: 2, l: 1, e: 1}

4.5 string operation method

String objects provide properties and methods for intercepting strings, connecting strings, and replacing strings. Common properties and methods of string objects are as follows:

methodeffect
concat(str1, str2, str3...)Connect multiple strings
slice(start,[ end])Intercept the substring from the start position to the end position. If there is no end parameter, intercept the string from start to the end of the string. Complex numbers are acceptable
substring(start[, end])Intercepts a substring from the start position to the end position, which is basically the same as slice, but does not receive negative values
substr(start[, length])Intercept the substring from the start position to the length
toLowerCase()Gets the lowercase form of the string
toUpperCase()Gets the uppercase form of the string
split([separator[, limit])Use the separator delimiter to separate strings into arrays, and limit is used to limit the number
replace(str1, str2)Use str2 to replace str1 in the string and return the replacement result. Only the first character will be replaced

concat example:

var s1 = "abc";
var s2 = "def";
var s3 = "123";
console.log(s1.concat(s2, s3));

The result is abcdef123

slice example:

var str="javascript Programming";
console.log(str.slice(4));//Intercepts characters from index 4 to the end of the string
console.log(str.slice(4, 9));//Intercept characters between 4 and 9
console.log(str.slice(-5,-3));

script programming
scrip
t process

substr example:

var str = "javascript Programming";
console.log(str.substr(0,10));

javascript

toLowerCase() example:

var str = "Javascript Programming";
console.log(str.toLowerCase());

javascript programming

toUpperCase() example:

var str = "javascript Programming";
console.log(str.toUpperCase());

JAVASCRIPT programming

split() example:

var phone = "135-1234-5678";
var arr = phone.split("-");
arr.forEach(elem => {
    console.log(elem);
})


replace example:

var str = "javascript Programming";
console.log(str.replace("java", "Action"));

Actionscript programming

[case] judge whether the user name is legal. The length of the user name is in the range of 3 ~ 10, and the sensitive word admin cannot appear in any case.

var username = prompt("enter one user name");
if (username.length < 3 || username.length > 10) {
    alert("The length of the user name is 3~10 between");
} else if (username.toLowerCase().indexOf("admin") !== -1) {
    alert("User name cannot contain sensitive words: admin");
} else {
    alert("The user name is legal");
}

5 value type and reference type

In JavaScript, simple data types (such as string, numeric, Boolean, undefined, null) are also called value types, and complex data types (objects) are also called reference types.

The characteristic of reference type is that only the address of a reference is saved in the variable. When assigning a value to a variable, the object is not copied, but the two variables point to the reference of the same object.

Example:

// Create an object and save the reference of the object through the variable obj1
var obj1 = { name: 'Xiao Ming', age: 18 };
// At this time, the object is not copied, but obj2 and obj1 variables refer to the same object
var obj2 = obj1;
// Compare whether two variables refer to the same object
console.log(obj2 === obj1);  // Output result: true
// Modify the properties of an object through obj2
obj2.name = 'Xiao Hong';
// Access the name attribute of the object through obj1
console.log(obj1.name);	    // Output result: Xiaohong

The result is:
true
Xiao Hong

After the above code is run, obj1 and obj2 variables refer to the same object. At this time, whether obj1 or obj2 is used to operate the object, the actual operation is the same object. As shown below:

When obj1 and obj2 point to the same object, if one of the variables (such as obj1) is re assigned to another object, or re assigned to another value, obj1 will no longer reference the original object, but obj2 is still referencing the original object.

var obj1 = { name: 'Xiao Ming', age: 18 };
var obj2 = obj1;
// obj1 points to a newly created object
obj1 = { name: 'Xiao Hong', age: 17 };
// obj2 still points to the original object
console.log(obj2.name);	 // Output result: Xiao Ming

The result is: Xiao Ming

be careful:
When an object is referenced by only one variable, if the variable is re assigned, the object will become the case without any variable reference. At this time, it will be automatically released by the JavaScript garbage collection mechanism.

If the property or method of an object is modified in the parameters of a function, the result of accessing it outside the function by referring to the variable of the object is also modified.

function change(obj) {
    obj.name = 'Xiao Hong';	// The properties of the object were modified within the function
}
var stu = { name: 'Xiao Ming', age: 18 };
change(stu);
console.log(stu.name);	// Output result: Xiaohong

The result is: Xiao Hong

Tags: Javascript Front-end

Posted on Tue, 23 Nov 2021 02:02:57 -0500 by TeamTJ