JavaScript foundation -- Super detail (built-in object and scope)

cjh_ code 2021-11-25 15:14:28

JavaScript Basics -- Hyperdetail ( Scope and object )_c.j.h_code The blog of -CSDN Blog

Catalog

6.1 Built-in objects

6.1.1 Built in object concept

6.1.2 Look up the documents

6.1.3 Math object

6.1.4 Date object

6.1.5 Array objects

6.1.6 String object

6.2 Simple data types and complex data types  

6.2.1 Simple data type

6.2.2 Complex data type

6.2.3 Heap and stack

6.2.4 Simple type transfer reference

6.2.5 Complex data type transfer parameters


6.1 Built-in objects

6.1.1 Built in object concept

        JavaScript The objects in are divided into 3 Kind of : Custom object Built-in objects Browser object . ​ The first two objects are JS Basics Content , Belong to ECMAScript; The third browser object belongs to JS Unique , JS API To explain built-in objects is to JS Some objects that come with language , These objects are used by developers , And provides some common or the most basic and necessary functions ( Properties and methods ), The biggest advantage of built-in objects is that they help us develop quickly

        JavaScript Provides multiple built-in objects :Math、 Date 、Array、String etc.

6.1.2 Look up the documents

         Search for documents : Learn how to use a built-in object , Just learn how to use its common members , We can learn by looking up documents , Can pass MDN/W3C To query . ​

        Mozilla Developer Network (MDN) Provides information about open network technology (Open Web) Information about , Include HTML、CSS And the world wide web and HTML5 Applied API.

6.1.3 Math object

        Math Object is not a constructor , It has properties and methods of mathematical constants and functions . Operations related to Mathematics ( Find the absolute value , integer 、 Maximum, etc ) have access to Math Members of the .

Property and method names function
Math.PI PI
Math.floor() Rounding down
Math.ceil() Rounding up
Math.round() rounding , Round to the nearest (-3.5 The result is -3)
Math.abs() The absolute value
Math.max()/Math.min Find the maximum and minimum
Math.random() The acquisition range is in [0,1) The random value in

         Be careful : The above method must use parentheses

         Gets a random integer in the specified range

function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

        Math.random() return [0,1) Random number between

The above code returns [min,max] Random number between

 6.1.4 Date object

        Date Objects and Math Different objects ,Date It's a constructor , Therefore, you need to instantiate before using the specific methods and properties .Date Instances are used to process date and time

To get the current time, you must instantiate :

var now = new Date();

Gets the date object of the specified time :

var future = new Date('2019/5/1');

Be careful : If the instance is created without passing in parameters , Then the date object obtained is the date object corresponding to the current time

 Date Methods and properties of the instance :

Method name explain
getFullYear() Get the year
getMonth() Get the current month (0-11)
getDate() Get date of day
getDay() Get the day of the week ( Sunday is 0- Saturday is 6
getHours() Get the current hour
getMinutes() Get the current minute
getSeconds() Get the current second

Date Instance to get the total number of millimeters :

         The meaning of total milliseconds : be based on 1970 year 1 month 1 Japan ( World standard time ) Milliseconds from .

// Instantiation Date object
var date = new Date();
// 1. Used to get the original value of the object
console.log(date.valueOf())
console.log(date.getTime())
// 2. Simple writing can do this
var now = + new Date();
console.log(now);
// 3. HTML5 Method provided in , Compatibility issues
var now = Date.now();
console.log(now);
// The result is the current time in milliseconds , The results are the same ( Ignore program run time )

6.1.5 Array objects

Literal measure :

var arr = [1,"test",true];

new Array():

var arr = new Array();

Be careful : In the above code arr It creates an empty array , If you need to use constructors Array Create a non empty array , You can pass in parameters when creating an array

The rules for parameter passing are as follows :

  • If only one parameter is passed in , The parameter specifies the length of the array

  • If multiple parameters are passed in , Then the parameter is called the element of the array

Check if it's an array :

        instanceof Operator : You can determine whether an object is an instance of a constructor .

var arr = [1, 23];
var obj = {};
console.log(arr instanceof Array); // true
console.log(obj instanceof Array); // false

        Array.isArray(): Used to determine whether an object is an array ,isArray() yes HTML5 Method provided in .

var arr = [1, 23];
var obj = {};
console.log(Array.isArray(arr)); // true
console.log(Array.isArray(obj)); // false

Add a method to delete array elements :

Method name explain Return value
push( Parameters 1...) Add one or more elements at the end , Note that the original array has been modified And returns the new length
pop() Delete the last element of the array , Reduce the length of the array 1, No parameter 、 Modified the original array Returns the value of the element it deleted
unshift( Parameters 1...) Add one or more elements... To the beginning of the array , Note that the original array has been modified And returns the new length
shift() Deletes the first element of the array , Array length reduction 1, No parameter 、 Modified the original array And returns the value of the first element

         Be careful :push、unshift To add elements ;pop、shift For the method of deleting elements .

Array sorting :

Method name explain Whether to modify the original array
reverse() Reverse the order of the elements in the array , No parameter This method will change the original array , Return a new array
sort() Sort elements of an array This method will change the original array , Return a new array

    Be careful :sort Method needs to pass in parameters to set the ascending order 、 null

  • If you pass in “function(a,b){ return a-b;}”, In ascending order
  • If you pass in “function(a,b){ return b-a;}”, In descending order

Array index method :

Method name explain Return value
toString() Convert an array to a string , Comma separated each item Returns a string
join(' Separator ') It is used to separate all elements in the array with parameters in parentheses, and convert each item into a string Returns a string

Be careful :join Method if it doesn't pass in parameters , According to “ , ” Patchwork elements .

Other methods :

Method name explain Return value
concat() Connect two or more arrays , Does not affect the original array Returns a new array
slice() Array truncation slice(begin,end) Returns a new array of intercepted elements
splice() Array delete splice( The first few starts , To delete the number of ) Returns a new array of deleted elements , Be careful : This will affect the original array

6.1.6 String object

Basic packaging type :

         To facilitate the operation of basic data types ,JavaScript Three special reference types are also provided :String、Number and Boolean.

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

// What's wrong with the following code ?
var str = 'andy';
console.log(str.length);

         The basic data type has no properties and methods , Objects have properties and methods , But the code above can be executed , This is because js Will wrap basic data types as complex data types

// 1. Generate temporary variables , Wrapping simple types into complex data types
var temp = new String('andy');
// 2. Assign to our declared character variable
str = temp;
// 3. Destroy temporary variables
temp = null;

The immutability of string :

         It means that the values in it are immutable , Although it seems that the content can be changed , But the address has changed , A new memory space has been opened up in memory .

         When you re assign a string variable , The string saved before the variable will not be modified , The string is still reassigned in memory , Will re open up space in memory , This feature is the immutability of strings . ​

         Because of the immutability of string , There are efficiency problems when splicing a large number of strings

Return position according to character :

Method name explain
indexOf(' Characters to find ', Starting position ) Returns the position of the specified content in the original string , If you can't find it, go back -1, The starting position is index Reference no.
lastIndexOf() Look backwards , Just find the first match

Returns the character according to the position :

         String through the basic wrapper type can call part of the method to manipulate the string

Method name explain Use
charAt(index) Returns the character in the specified position (index The index number of the string ) str.charAt(0)
charCodeAt(index) Gets the... Of the character at the specified location ASCII code (index Reference no. ) str.charCodeAt(0)
str[index] Gets the character at the specified location HTML5,IE8+ Support and charAt() equivalent

String operation method :

         String through the basic wrapper type can call part of the method to manipulate the string

Method name explain
concat(str1,str2,str3...) concat() Method to connect two or more strings , String concatenation , Equivalent to +
substr(start,length) from start Position start ( Reference no. ),length Take the number of
slice(start,end) from start Position start , Intercept to end Location ,end Can't get ( They're both index numbers )
substring(start,end) from start Position start , Intercept to end Location ,end Can't get , Basic and slice identical , But negative values are not accepted

replace() Method :

        replace() Method is used to replace some characters with others in a string .

character string .replace( Replaced string , String to replace with );

split() Method :

        split() Method is used to segment strings , It splits strings into arrays . After the segmentation , It returns a new array .

character string .split(" Split characters ");

6.2 Simple data types and complex data types  

6.2.1 Simple data type

         Simple type Basic data type Value type ): In storage time, the value itself is stored in the variable , Include string ,number,boolean,undefined,null.

6.2.2 Complex data type

         Complex data type ( Reference type ): At the time of storage, only the address is stored in the variable ( quote ), adopt new Keyword created objects ( System object 、 Custom object ), Such as Object、Array、Date etc. ;

6.2.3 Heap and stack

The difference between heap and stack space allocation :

  1. Stack ( operating system ): The operating system automatically allocates and releases the parameter values of stored functions 、 The value of a local variable, etc . It operates like a stack in a data structure ;
  2. Simple data types are stored in the stack
  3. Pile up ( operating system ): Store complex types ( object ), Release is usually assigned by the programmer , If programmers don't release , Recycling by garbage collection mechanism .

  How simple data types are stored :

         The data of the value type variable is directly stored in the variable ( Stack space ) in .

  How complex data types are stored :

         Reference type variable ( Stack space ) There's an address in it , Real object instances are stored in heap space .

 6.2.4 Simple type transfer reference

         The formal parameter of a function can also be regarded as a variable , When we pass a value type variable as a parameter to a function's formal parameter , In fact, the value of the variable in the stack space is copied to the formal parameter , Then make any changes to the formal parameters within the method , Will not affect the external variables of .

function fn(a) {
a++;
console.log(a); //11
}
var x = 10;
fn(x);
console.log(x);//10

6.2.5 Complex data type transfer parameters

         The formal parameter of a function can also be regarded as a variable , When we pass a reference type variable to a formal parameter , In fact, it copies the heap address stored in the stack space of the variable to the formal parameter , Formal parameters and arguments actually store the same heap address , So it operates on the same object .

function Person(name) {
this.name = name;
}
function f1(x) { // x = p
console.log(x.name); // 2. Lau Andy
x.name = " Jacky Cheung ";
console.log(x.name); // 3. Jacky Cheung
}
var p = new Person(" Lau Andy ");
console.log(p.name); // 1. Lau Andy
f1(p);
console.log(p.name); // 4. Jacky Cheung 
Please bring the original link to reprint ,thank
Similar articles

2021-11-25

2021-11-25

2021-11-25

2021-11-25

2021-11-25

2021-11-25

2021-11-25