25-basic JavaScript ⑤ (built-in objects, simple data types and complex data types)

Posted by mightymaster on Fri, 24 Dec 2021 04:56:58 +0100

1. Built in objects

1.1 built in objects

There are three kinds of objects in JavaScript: custom object, built-in object and browser object

The first two objects are the basic content of JS and belong to ECMAScript; The third browser object is unique to JS. JS API explains that built-in objects refer to some objects of JS language. These objects are used by developers and provide some common or most basic and necessary functions (properties and methods). The greatest advantage of built-in objects is to help us develop quickly

JavaScript provides several built-in objects: Math, Date, Array, String, etc

1.2 checking documents

Mozilla Developer Network (MDN) provides information about Open Web technology (Open Web), including HTML, CSS and API s for World Wide Web and HTML5 applications.
MDN:https://developer.mozilla.org/zh-CN/

1.3 Math objects

Property, method namefunction
Math.PIPI
Math.floor()Round down
Math.ceil()Round up
Math.round()The rounded version is rounded to the nearest. Note - 3.5. The result is - 3
Math.abs()absolute value
Math.max()/Math.min()Find the maximum and minimum values
Math.random()Gets a random value in the range [0,1]

Get a random integer between two numbers:

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //Excluding maximum value and including minimum value
}

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; //Including maximum and minimum 
}

1.4 Date object

Date is a constructor, so you need to instantiate it before you can use its specific methods and properties.

//If no parameter is passed in when creating an instance, the date object obtained is the date object corresponding to the current time
var now = new Date();
var date1 = new Date(2021,12,23);
var date2 = new Date(2021-12-23 15:05:00);

Methods and properties of Date instance:

Method nameexplain
getFullYear()Get the year
getMonth)Get the month (0-11)
getDate()Get the date
getDay()Get the week (0-6, Sunday is 0)
getHours()When getting
getMInutes()Get points
getSeconds()Get seconds

Get total milliseconds: Based on milliseconds since January 1, 1970 (world standard time)

// Instantiate Date object
var date = new Date();
// 1. Used to obtain the original value of the object
console.log(date.valueOf())	
console.log(date.getTime())	
// 2. Simple writing can do this
var now = +new Date();			
// 3. The method provided in HTML5 has compatibility problems
var now = Date.now();

Countdown effect:

function countDown(time) {
	var nowTime = +new Date(); // Returns the total number of milliseconds of the current time
	var inputTime = +new Date(time); // Returns the total number of milliseconds of user input time
	var times = (inputTime - nowTime) / 1000; // times is the total number of seconds remaining 
	var d = parseInt(times / 60 / 60 / 24); // day
	d = d < 10 ? '0' + d : d;
	var h = parseInt(times / 60 / 60 % 24); //Time
	h = h < 10 ? '0' + h : h;
	var m = parseInt(times / 60 % 60); // branch
	m = m < 10 ? '0' + m : m;
	var s = parseInt(times % 60); // Current seconds
	s = s < 10 ? '0' + s : s;
	return d + 'day' + h + 'Time' + m + 'branch' + s + 'second';
}
console.log(countDown('2022-1-1 00:00:00'));
var date = new Date();
console.log(date);

1.5 array objects

There are two ways to create an array:

// 1. Use array literal
var arr1 = [1, 2, 3];
// 2. Use new Array()
var arr2 = new Array();  // An empty array was created
var arr3 = new Array(2);  // An empty array of length 2 was created
var arr4 = new Array(1,2,3); // Equivalent to array [1,2,3] 

Check whether it is an array:

var arr = [1, 23];
var obj = {};
//instanceof can determine whether an object is an instance of a constructor
console.log(arr instanceof Array); // true
console.log(obj instanceof Array); // false
//Array.isArray() is used to determine whether an object is an Array.isArray() is a method provided in HTML5
console.log(Array.isArray(arr));   // true
console.log(Array.isArray(obj));   // false

Add or remove array elements:

Method nameexplainreturn
Push (parameter 1, parameter 2...)Modify the original array by adding one or more elements to the end of the arrayReturns the added length
Unshift (parameter 1, parameter 2...)Add one or more elements to the beginning of the array to modify the original arrayReturns the added length
pop()Delete the last element of the array, reduce the length of the array by 1, have no parameters, and modify the original arrayReturns the value of the deleted element
shift()Delete the first element of the array, reduce the length of the array by 1, have no parameters, and modify the original arrayReturns the value of the deleted element

Array sorting:

var arr = [13, 4, 77, 1, 7];
// 1. The reverse() flip array has no parameters
console.log(arr.reverse());//[7, 1, 77, 4, 13]
// 2. Array sorting (bubble sorting)
//Ascending order
arr.sort(function(a, b) {
	return a - b;
});
console.log(arr);//[1, 4, 7, 13, 77]
//Descending order
arr.sort(function(a, b) {
	return b - a;
});
console.log(arr);//[77, 13, 7, 4, 1]

Array index method:

Method nameexplainreturn
indexOf()Finds the first index of the given element in the arrayReturns an index number if one exists, otherwise - 1 is returned
lastIndexOf()Finds the last index of the given element in the arrayReturns the index number in, otherwise returns - 1

Convert array to string:

Method nameexplainreturn
toString()Convert the array to a string, separating each item with a commaReturns a string
join('separator ')Converts an array into a string, specifying a separator to separate each itemReturns a string

other:

Method nameexplainreturn
concat()Connect two or more arrays without affecting the original arrayReturns a new array
slice()Shallow copy, array interception slice(begin,end) does not contain end and does not affect the original arrayReturns a new array of intercepted parts
splice()Deleting a splice from the array (starting from the first few, the number to be deleted) will change the original arrayReturns a new array of deleted parts

1.6 string objects

Basic package type:
To facilitate the manipulation of basic data types, JavaScript also provides three special reference types: String, Number, and Boolean.

The basic wrapper type is to wrap a simple data type into a complex data type, so that the basic data type has properties and methods.

var str = 'andy';
console.log(str.length);

In principle, basic data types have no attributes and methods, while objects have attributes and methods, but the above code can be executed because js will package basic data types as complex data types. The execution process is as follows:

// 1. Generate temporary variables and wrap simple types into complex data types
var temp = new String('andy');
// 2. Assign a value to the character variable we declare
str = temp;
// 3. Destroy temporary variables
temp = null;

Immutability of string:
When the string variable is re assigned, the previously saved string of the variable will not be modified and will still be in memory; Re assigning a value to a string will re open up space in memory, which is characterized by the immutability of the string.
Due to the immutability of strings, there will be efficiency problems when a large number of strings are spliced

Return position according to character:
(all methods of the string will not modify the string itself (the string is immutable), and a new string will be returned after the operation is completed)

Method nameexplainreturn
indexOf('character to find ', [starting position])Find the first index of the given element in the string from the given position. If no location is given, find it from the beginningReturns an index number if one exists, otherwise - 1 is returned
lastIndexOf()Finds the last index of a given element in a stringReturns the index number in, otherwise returns - 1

Return characters according to position:

Method nameexplainuse
charAt(index)Returns the character at the specified position (index is the index number of the string)str.charAt(0)
charCodeAt(index)Returns the ASCII code of the character at the specified positionstr.charCodeAt(0)
str[index]Gets the character at the specified positionHTML5,IE8 + support

String operation method:

Method nameexplain
concat(str1,str2,...)Used to splice multiple strings
substr(start,length)Starting from the start position (index number), take the number of length s
slice(start,end)Start from the start position and intercept to the end position (excluding end)
substring(start,end)Starting from the start position, intercept to the end position (excluding end), and do not accept negative values

replace() method:
The replace() method is used to replace some characters with others in the string. Its format is as follows: (only replace the first)

character string.replace(The string to be replaced, the string to be replaced with);

split() method:
The split() method is used to split strings, which can be split into arrays. After segmentation, a new array is returned. Its format is as follows:

character string.split('Split character');

2. Simple data type and complex data type

2.1 simple data types

Simple type (basic data type, value type): when storing, the value itself is stored in the variable, including string, number, boolean, undefined, null (empty object).

2.2 complex data types

Complex data type (reference type): during storage, only the address (Reference) is stored in the variable, and the objects (system objects, user-defined objects) created through the new keyword, such as Object, Array, Date, etc.

2.3 stack

  • Stack space allocation difference:

1. Stack (operating system): the operating system automatically allocates and releases the parameter values and local variable values of the stored function. Its operation mode is similar to the stack in the data structure;

2. Heap (operating system): it stores complex types (objects), which are generally allocated and released by the programmer. If the programmer does not release them, they are collected by the garbage collection mechanism.

  • Storage of simple data types:

The data of value type variables is stored directly in variables (stack space)

  • Storage of complex data types:

Reference type variables (stack space) store addresses, and real object instances are stored in heap space

2.4 simple data type parameter transfer

The formal parameter of a function can also be regarded as a variable. When we pass a value type variable as a parameter to the formal parameter of a function, we actually copy the value of the variable in the stack space to the formal parameter. Then any modification to the formal parameter inside the method will not affect the external variable.

2.5 complex data type parameter transfer

The formal parameter of a function can also be regarded as a variable. When we pass a reference type variable to the formal parameter, we actually copy the heap address saved by the variable in the stack space to the formal parameter. The formal parameter and the actual parameter actually save the same heap address, so we operate on the same object.

Topics: Javascript Front-end css