JS built in constructor Boolean number string math date array

Posted by ngolehung84 on Fri, 18 Feb 2022 13:52:14 +0100

JS built in object constructor

[the external chain image transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-C1Z5e4H4-1620368930653)(C:\Users \ Wang Xiu \ appdata \ roaming \ typora user images \ image-20210408114150517. PNG)]

This figure shows the constructor's own prototype chain

Online documentation: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects

Built in constructor, mainly mastering the properties and methods of built-in constructor instances

A built-in constructor is an instance of a built-in object.

1 Boolean

There are three ways to create data of Boolean type, just like array

// Direct quantity method
var b1 = true;               //true

// Constructor mode (with the function of data type conversion)
var b2 = new Boolean(true);   //Boolean

// function
var b3 = Boolean(false);     //false

2 Number

Properties and methods of the Number instance

toFixed()		Returns the decimal place of the specified number of digits. The parameter is set to the decimal place reserved. If there is no parameter, it is rounded by default; Rounding rules.
toString()		Convert the number to other forms, and the parameter specifies the base.
// Create a data of type Number
var num = 123.67;
console.log(num);
// Number instance toFixed() (returns a string, rounded to decimal)
console.log(num.toFixed(1));  //123.7
console.log(num.toFixed(5));  //123.67000
console.log(num.toFixed());   //124 integers are also rounded
console.log('');
// toString() can be converted to hexadecimal
console.log(num.toString());  //123.67
console.log(num.toString(2)); //1111011.10101011100001010001111010
console.log(num.toString(8));  //173.5270243656050754

Properties and methods of the Number constructor itself

Number.MAX_VALUE		obtain JS The maximum value that can be represented in
Number.MIN_VALUE		obtain JS The smallest value that can be represented in
 // The maximum and minimum number that can be represented in js
        console.log(Number.MAX_VALUE); //1.7976931348623157e+308
        console.log(Number.MIN_VALUE);  //5e-324

3 String

Properties and methods of String instances

length		Property, read-only, gets the length of the string (the number of characters in the string)

charAt(index)			Take out the characters of the specified index for general use [] Grammatical substitution.
charCodeAt(index)		Gets the of the specified index character uncode code.
indexOf(value)			return vlue The position of the first occurrence in the string.
lastIndexOf(value)  	return value The position of the last occurrence in the string.
slice(start [,end])		Intercept the string. The first parameter specifies the starting position of interception, the second parameter specifies the ending position (the character of the ending position is not included in the result), and the second parameter is not specified to intercept to the end of the string.
substring(start [,end]) with slice As like as two peas.
substr(start, [,len])   Intercept string, and slice In contrast, the second parameter specifies the length of the interception and does not specify the second parameter to intercept to the end of the string
split([Separator])		  Separate strings into arrays.
toUpperCase()			Convert all strings to uppercase.
toLowerCase()			Convert all strings to lowercase.

be careful:

  1. You can usually use indexOf() and lastIndexOf() to determine whether a value is included in the string. If - 1 is returned, it is not included.
  2. The String constructor of codechart() and the method of codechart() are mutually operant.

Properties and methods of the String constructor itself

String.fromCharCode(Digital coding)		Return specified unicode Encoding corresponding characters
// How to create a String type
var msg = 'Hello,Fangfang';

// Get a character according to the index
console.log(msg.charAt(3));   //l

// Gets the position of a character in the string
console.log(msg.indexOf('l'));     // First occurrence position 2
console.log(msg.lastIndexOf('l')); // Last occurrence position 3
console.log(msg.indexOf('wang'));   // The value to find does not exist - 1

// Intercept string
console.log(msg.slice(2));        //Li llo, Fangfang
console.log(msg.slice(2,5));      // llo looks after his head and ignores his tail
console.log(msg.substring(2));    //Li llo, Fangfang
console.log(msg.substring(2,5));  //llo
console.log(msg.substr(2));       // llo, Fangfang intercepts from the position of index 2 to the end
console.log(msg.substr(2, 5));    // llo, 5 is the length, not the interception position

// split can divide the string into an array, specify the separator, and empty the string
console.log(msg.split());      //["Hello, Fangfang"]
console.log(msg.split(' '));   //["Hello, Fangfang"]
console.log(msg.split(''));    //["H", "e", "l", "l", "o", "Fang", "Fang"]
console.log(msg.split('l'));   // ["he", "O, Fangfang"]

// toggle case
// Convert all strings to uppercase
console.log(msg.toUpperCase());   //HELLO, Fangfang
// Convert all strings to lowercase
console.log(msg.toLowerCase());   //hello, Fangfang
// Unicode character
console.log('e of unicode code:', msg.charCodeAt(1));  //101
console.log('Aromatic uncode code:', 'Fragrant'.charCodeAt(0));  //33459
// Properties and methods of the constructor itself
// According to a unicode code, the corresponding characters are obtained
console.log(String.fromCharCode(65));    //A
console.log(String.fromCharCode(33465));  //Celery

4 Math

Math.PI		Property to get the PI

Math.abs()		Take absolute value
Math.sqrt()		Open square
Math.pow()		Find power
Math.round()	Rounding
Math.floor()    Round off
Math.ceil()     Round to one
Math.max()      Take the largest of all parameters
Math.min()      Take the smallest of all parameters
Math.random()	Take a random number and the result is 0~1 Decimals (0 has a certain probability of being random, but 1 is never possible)

Rules for random numbers:

  1. Randomly take an integer between 0 and N: math floor(Math.random() * (n + 1))
  2. Randomly take the integer between S and N: math floor(Math.random() * (n - s + 1)) + s
// Math is an object
console.log(Math);
console.log('');
// PI Pi PI
console.log('PI:',Math.PI);  //3.141592653589793

// Mathematics related methods
console.log('-123 Absolute value of:',Math.abs(-123))   //123
console.log('Square footage:', Math.sqrt(100));       //10
console.log('Power:', Math.pow(2, 3));       //8

// Methods of taking integer (three types)
console.log('Rounding:', Math.round(123.99)); //124
console.log('Rounding:', Math.floor(123.99));    //123 // floor is the same as ParsInt (rounded)
console.log('Rounding to the next:', Math.ceil(123.0009));   //124

// Take the maximum and minimum values of the parameters
console.log(Math.max(123, 23, 345, 678, 908, 100));  //908
console.log(Math.min(123, 23, 345, 678, 908, 100));  //23

// Take a random number, and the result is between 0-1 decimals (regardless of the head and tail, 0 has a certain probability)
console.log(Math.random());
// Random integer between 0-9 * 10 rounded off
console.log('Random 0~9 Integer between:',Math.floor(Math.random()*10));
// Random integer between 0-15
console.log('Random 0~15 Integer between:', Math.floor((Math.random() * 16)));
// The integer between random 8-27 takes 0-19 first, and then + 8
console.log('Take 8 at random ~ 27 Integer between:', Math.floor(Math.random() * 20) + 8);

5 Date

Create date date time object

var today = new Date();
var birthday = new Date('December 17, 1995 03:24:00');
var birthday = new Date('1995-12-17T03:24:00');
var birthday = new Date(1995, 11, 17);
var birthday = new Date(1995, 11, 17, 3, 24, 0);

Properties and methods of the Date instance

getFullYear()			The year contained in the datetime object
getMonth()				The month contained in the date time object. The value range is 0 ~ 11
getDate()			    The day contained in the date time object (the day of each month)
getDay()				The day of the week contained in the datetime object
getHours()				The hours contained in the datetime object
getMinutes()			The minute contained in the datetime object
getSeconds()			The number of seconds contained in the datetime object
getMilliseconds()		The number of milliseconds contained in the datetime object

getUTC...               Get the year, day, hour, minute and second of the zero time zone

getTime()			Gets the number of milliseconds (timestamp) from the date time object to 0:0:0 on January 1, 1970

set ...					Set the year, month, day, hour, minute and second of the date time object
setUTC...				Set the year, month, day, hour, minute and second of the zero time area of the date time object
setTime()				Set the date time object in the form of timestamp

Properties and methods of the Date constructor itself

Date.now()				Timestamp at this moment
Date.UTC()				To specify the time stamp of the date and time, 6 parameters need to be set.
 // Create datetime object (datetime at this moment)
 var date1 = new Date();
 var date2 = new Date('2020-10-01T10:56:00');
 var date3 = new Date(2020,2,1,12);
 console.log(date1);  //Wed Mar 31 2021 20:19:06 GMT+0800 (China standard time)
 console.log(date2);  //Thu Oct 01 2020 10:56:00 GMT+0800 (China standard time)
 console.log(date3);  //Sun Mar 01 2020 12:00:00 GMT+0800 (China standard time)
 
 // Get to get the current time separately
 console.log('Ad:',date1.getFullYear());  //2021
 console.log('Month:', date1.getMonth() + 1);     //3
 console.log('Date:', date1.getDate());          //31
 console.log('Week:', date1.getDay());         //3
 console.log('When:', date1.getHours());         //20
 console.log('Score:', date1.getMinutes());       //22
 console.log('Seconds:', date1.getSeconds());       //24
 console.log('millisecond:', date1.getMilliseconds()); //916

// UTC gets the time of the zero time zone
// Get time stamp: on January 1, 1970, the first operating system was born in the number of milliseconds from date1, 0 minutes and 0 seconds, which is convenient to calculate the time difference
console.log(date1.getUTCFullYear());   //2021
console.log(date1.getUTCHours());      //12

// set sets the time in date1
date1.setFullYear(1980);
date1.setUTCHours(18);
// Set timestamp
date1.setTime(1000000000000);
console.log(date1);    //Sun Sep 09 2001 09:46:40 GMT+0800 (China standard time)

// creating date objects 
var date4 = new Date(98723423423);
console.log(date4);   //Fri Feb 16 1973 23:10:23 GMT+0800 (China standard time)

// Get the timestamp at this moment 
console.log('Timestamp at this moment:', Date.now());

// Specifies the timestamp of the date time UTC or directly define the time variable (output date.getTime)
console.log('Timestamp of the specified date and time:', Date.UTC(2022, 8, 1, 10, 10, 0));

Find the time stamp of 10:10:0 on December 2, 1999

// The first method is to create a date time object containing the specified time and obtain the timestamp
var date = new Date(1999, 11, 2, 10, 10);  // new Date('1999-12-02T10:10:00')
date.getTime();

// The second way is to use the method UTC() of the Date constructor itself
Date.UTC(1999, 11, 2, 10, 10);

6 Array

Accessor method of array instance

Accessor method refers to calling the method, the object itself will not be modified, and the calculation result will be given as the return value of the method. Generally, there are only accessor methods in an object.

concat()		Merge arrays and return the merged array; One or more parameters can be specified.
slice()			Intercept the array and return the intercepted array; The first parameter specifies the location where the interception starts, and the second parameter specifies the location where the interception ends (if not specified, the interception ends)
join()			Merge the string into an array and return it; You can specify a separator (comma by default)

Modifier method of array instance

Modifier method means that when this method is called, the object itself will be modified. Only array objects have modifier methods.

push()		Adding one or more elements after the array returns the length of the array after adding the new array
unshfit()	Add one or more elements to the front of the array and return the length of the array after adding the new array
pop()		Delete the last element of the array and return the deleted element.
shift()		Delete the first element of the array and return the deleted element.
splice()	Adds, removes, or replaces elements to an array. Returns an array containing the deleted elements (an empty array if no elements are deleted)
sort()		Sort the array. Returns an ordered array.
reverse()	Flip the array. Returns the array after flipping.
//  Create string
var msg = 'hello';
//  Create array
var arr = [100,200,300,400,600,150];
msg.slice(2,4);
console.log(msg);  //hello

arr.push('Fangfang');
console.log(arr);  //[100200300400600150, 'Fangfang'];
// Accessor mode
// Merge array
console.log(arr.concat(['a','b','c']));
console.log(arr.concat(['a','b','c'], ['A','B'], [1,2,3,4]));
// Intercept array
console.log(arr.slice(2, 5));  //[300,400,600]
console.log(arr.slice(2));     //[300400600150, 'Fangfang']
// You can specify a separator by combining arrays into strings
console.log(arr.join());     //100200300400600150, Fangfang
console.log(arr.join('->')); //100 - > 200 - > 300 - > 400 - > 600 - > 150 - > Fangfang
console.log(arr.join(''));   //100200300400600150 Fangfang
console.log(arr);
// Modifier returns the deleted array
console.log(arr.push('great mercy'));           //8 return value length
console.log(arr.unshift('Cao Cao', 'Lv Bu')); //10
console.log(arr.pop());     //Great sorrow returns the deleted element 
console.log(arr.shift());   //Cao Cao returns the deleted element
console.log(arr);
console.log(arr.splice(2, 0, 'Zhuge Liang'));  //Deleted element
console.log(arr);            
console.log(arr.sort());         //sort
console.log(arr);
console.log(arr.reverse());      //Flip the order of rows
console.log(arr);
// reverse flipping an array is the opposite of sorting sort

Method of adding array instances in ES5

These methods are also accessor methods! Callback functions are required as parameters.

forEach()			For array traversal, a callback function is required as a parameter
filter()			Extract the elements that meet the conditions from the original array to form a new array and return it. A callback function is required as a parameter; Return value of callback function( true perhaps false)Determines whether the corresponding element is in the new array
map()			Return a new array with the same number of elements as the original array. A callback function is needed as the callback function. What is returned by the callback function is what is the element of the new array.
every()	Returns a Boolean value that requires each element to meet the conditions true,A callback function is required as an argument.
some()	Returns a Boolean value, as long as an element satisfies the condition true,A callback function is required as an argument.
reduce()			For comprehensive calculation, a callback function is required as a parameter, and the second parameter specifies the initial value
 The callback function receives three parameters:①Result of last callback ②Current element ③ Indexes
reduceRight()		with reduce Similarly, knowledge traverses from back to front.
indexOf()			Returns the position of the first occurrence of the specified element in the array.
lastIndexOf()		Returns the position of the last occurrence of the specified element in the array.
var users = [
{
name: 'Fangfang',
age: 18,
address: 'Shanghai'
},
{
name: 'great mercy',
age: 78,
address: 'cave'
},
{
name: 'Cao Cao',
age: 48,
address: 'Xu Chang'
},
{
name: 'Lv Bu',
age: 38,
address: 'Baotou'
},
{
name: 'Cao Pi',
age: 12,
address: 'Xu Chang'
},
{
name: 'Little sad',
age: 31,
address: 'cave'
}
];
console.log(users);

// forEach traversal array
users.forEach(function(item, index) {
console.log(item, index);
});

// filter gets the adults in the user
var fUsers = users.filter(function(item, index) {
return item.age >= 18;
});
console.log(fUsers);

// map extracts information from the original array to get a new array, age + 1
var mUsers = users.map(function(item, index) {
// return item.name;
item.age ++;
return item;
});
console.log(mUsers);

// One unsatisfied addition of every is false. Are all users adults 
var res = users.every(function(item, index) {
return item.age >= 18;
});
console.log(res);   //false

// some has a condition that is true. Whether there are users living in the cave
var res = users.some(function(item, index) {
return item.address === 'cave';
});
console.log(true);  //true

// Reduce (reduce right) calculates the sum of all elements (the return value of the previous element, the current one, and the index)
var nums = [100,200,300,400];
var sum = nums.reduce(function(prev, item, index) {
return prev + item;
}, 0);
console.log(sum);   //1000

// Users to calculate the age and age of all users
var ageSum = users.reduce(function(prev, item) {
return prev + item.age;
}, 0);
console.log(ageSum);   //231

// users.reduceRight()

// indexOf() lastIndexOf() -1 does not contain > = 1 is contains (index)
// indexOf() lastIndexOf()
console.log(nums.indexOf(400));   //3
console.log(nums.indexOf(4000));    -1

Topics: Javascript