current position:Home>[dry goods sharing | suggestions collection] 2W word exploding liver detailed JavaScript object

[dry goods sharing | suggestions collection] 2W word exploding liver detailed JavaScript object

2021-08-27 02:27:25 Please call me Ken

Appreciate meeting Hello I am ken

author : Please call me ken
link : Please call me ken Home link
source :CSDN
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .

About foreword :

Part of the content and pictures of the article come from the Internet , If you have any questions, please contact me ( The official account is in the main page )
This blog is suitable for those who have just come into contact with JS As well as a long time did not see want to review the small partner .

About the content :

JavaScript object

5.1_ Initial object

5.1.1_ What is an object

for example : stay JavaScript Describes a mobile phone object in , The properties and methods of the mobile phone are as follows :

  • Mobile phone properties : Color 、 weight 、 Screen size .
  • How to use mobile phones : Make a phone call 、 texting 、 Watch videos 、 Listen to the music .
    In the code , An attribute can be regarded as a variable stored in an object , Use “ object . Property name ” Express ; Method can be regarded as a function stored in an object , Use “ object . Method name ()” Visit .
//  Suppose there is a mobile phone object p1, Created through code 
var p1 = {
    
color: ' black ',
weight: '188g',
screenSize: '6.5',

call: function (num) {
    
console.log(' Phoning '+num);
},

sendMessage: function (num, message) {
    
console.log (' to '+ num + ' texting , The content is :' + message);
},

playVideo: function() {
    
console.log (' Play the video ');
},

playMusic: functlon() {
    
console.log (' Play music ');
}

};

// Visit to p1 Properties of 
console.log (pl.color);     //  Output results :" black ", Indicates that the color of the phone is black 
console.log (p1.weight);    //  Output results : "188g", Indicates that the weight of the mobile phone is 188 g 
console.log (p1.screenSize);//  Output results :"6.5", Indicates that the screen size of the mobile phone is 6.5 Inch 

// call p1 Methods 
p1.call('123');           //  Call the calling method of the mobile phone , The dialing number is 123
p1.sendMessage('123', 'hello'); //  Give me the phone number 123 texting , The content is hello
p1.playVideo();    //  Call the video playing method of the mobile phone 
p1.playMusic();    //  Call the music playing method of the mobile phone 

As can be seen from the above code , Object properties and variables are used in a similar way , The method of the object is similar to that of the function .
A series of properties and methods can be collected through objects , Use a simple variable name p1 To express .

5.1.2_ Create an object using literals

stay JavaScript in , The literal value of an object is in curly braces “{" To wrap the members in the object , Each member uses "key:value" To preserve ,key Represents the property name or method name ,value Represents the corresponding value . Multiple object members are separated by “," separate .

Case study :

//  Create an empty object 
var obj = {
    };
//  Create a student object 
var stul = {
    
name: ' Xiao Ming ',  // name  attribute 
age: 18,       // age attribute 
sex: ' male ',     // sex attribute 

sayHello: function () {
      // sayHello Method 
console.log ('Hello');
}

};

In the above code ,obj Is an empty object , The object has no members .stu1 Object containing 4 Members , Namely name、age、sex and sayHello, among name,age and sex Is an attribute member ,sayHello Is a method member .

5.1.3_ Access object properties and methods

After creating the object , You can access the properties and methods of the object .
The sample code is as follows :

// Access the properties of the same object ( grammar 1)
console.log (stul.name);   //  Output results : Xiao Ming 
// Access the properties of the same object ( grammar 2)
console.log (stul['age']); //  Output results :18

// Method of calling object ( grammar 1)
stul.sayHello();        //  Output results : Hello
// Method of calling object ( grammar 2)
stul['sayHello']();     //  Output results : Hello 

If the member name of the object contains special characters , You can use a string to represent ,
The sample code is as follows :

var obj = {
    
'name-age': ' Xiao Ming -18'
};
console.log (obj['name-age']);  
//  Output results :" Xiao Ming -18"

JavaScript The object has dynamic characteristics . If an object has no members , Users can manually assign properties or methods to add members ,
Specific examples are as follows :

var stu2 = {
    };      //  Create an empty object 
stu2.name = 'Jack';  //  Add... To the object name attribute 
stu2.introduce = function() {
         //  Add... To the object introduce Method 
alert ('My name is ' + this.name);//  Use... In methods this Represents the current object 
};

alert (stu2.name);// visit name attribute , Output results : Jack
stu2.introduce();// call introduce() Method , Output results :My name is Jack

In the above code , In the method of an object, you can use this To represent the object itself , therefore , Use this.name You can access the... Of the object name attribute .

If you access a property that does not exist in the object , Returns the undefined.
The sample code is as follows :

var stu3 = {
    };      // Create an empty object 
console.log(stu3.name); // Output results : undefined

5.1.4_ utilize new Object Create objects

When I was studying arrays , We know that we can use new Array Create an array object . An array is a special object , If you want to create an ordinary object , Then use new Object Create .

The sample code is as follows :

var obj = new Object(); // Created an empty object 
obj.name = ' Xiao Ming ';  // After creating the object , Add members to the object 
obj.age = 18;
obj.sex = ' male ';
obj.sayHello = function(){
    
console.log('Hello');
};

5.1.5_ Using constructors to create objects

The literal method learned earlier is only suitable for creating an object , When you need to create multiple objects , Also write every member of the object , Obviously more troublesome , therefore , You can use constructors to create objects . The syntax for using constructors to create objects is “new Constructor name ()”, Arguments can be passed to the constructor in parentheses , If there are no parameters , Parentheses can be omitted .

actually ,“new Object()” Is a way to create objects using constructors ,Object Is the name of the constructor , But this creates an empty object .

The basic grammar is as follows :

// Write constructors 
function  Constructor name () {
    
this. attribute  =  attribute ;
this. Method  = function() {
    
// Method body 
};
}

// Use constructors to create objects 
var obj = new  Constructor name ();

In the above grammar , In the constructor this Represents the newly created object , In the constructor, you can use this To add members to the newly created object . It should be noted that , The name of the constructor is recommended to be capitalized .

Case study :

//  Write a Student Constructors 
function Student (name, age) {
    
this.name = name;
this.age = age;
this.sayHello = function() {
    
console.log (' Hello , My name is ' + this.name);
};
}

// Use Student Constructor create object 
var stul = new Student(' Xiao Ming ', 18);
console.log(stul.name);         //  Output results : Xiao Ming 
console.log(stu1.sayHello());   //  Output results : Hello , My name is Xiao Ming 
var stu2 = new Student(' Xiaohong ', 17);
console.log(stu2.name);         //  Output results : Xiaohong 
console.log(stu2.sayHello());   //  Output results : Hello , My name is Xiao Hong 

JavaScript Constructors in are similar to traditional object-oriented languages ( Such as Java) Class in (class), therefore JavaScript Some terms in object-oriented programming can also be used in .

  • abstract : Extract the common features of a class of objects , Write a construction function ( class ) The process of , It's called abstraction .

  • Instantiation : Using constructors ( class ) The process of creating objects , It's called instantiation .

  • example : If stu1 The object is Student Constructor created , be stu1 The object is called Student Instance of constructor ( Or instance object ).

tip :
In some documents , Methods in objects are often referred to as functions , Or call the construction function constructor or construction method , We just need to understand that these terms refer to the same thing .

Learn more recruit : Static members

There are static in object-oriented programming ( static ) The concept of ,JavaScript No exception .JavaScript Static members in , It refers to the properties and methods of the constructor itself , You don't need to create an instance object to use .

Let's demonstrate the creation and use of static members through code :

function Student(){
    
}

Student.school = 'x university ';       //  Add static properties school
Student.sayHello = function() {
     //  Add static methods sayHello
console.log('Hello');
};

console.log(Student.school);    // Output results :x university 
Student.sayHello();             // Output results :Hello

5.1.6_ Traversing the properties and methods of an object

Use for.in Syntax can traverse all properties and methods in an object ,
The sample code is as follows :

//  Prepare an object to be traversed 
var obj = {
    name:' Xiao Ming ', age:18, sex:' male '};

//  Traverse obj object 
for(var k in obj){
    
//  adopt k You can get the property name or method name in the traversal process 
console.log(k);        //  Output... In sequence :name、age、sex
console.log (obj[k]);  //  Output... In sequence : Xiao Ming 、18、 male 
}

 Insert picture description here

In the above code ,k It's a variable name , You can customize , Customarily named k perhaps key, Indicates the key name . When traversing to each member , Use k To get the name of the current member , Use obj[k] Get the corresponding value . in addition , If the object contains methods , You can use the “ obj[k]() " To call .

Learn more : Determine whether the object member exists

When you need to judge whether a member in an object exists , have access to in Operator ,
Case study :

var obj = (name:'Tom', age: 16);
console.log('age' in obj);   //  Output results : true
console.log('gender' in obj);//  Output results : false

As can be seen from the above code , Returns... When the member of the object exists true , Return... When not present false.

5.2_ Built-in objects

For the convenience of program development ,JavaScript Provides many commonly used built-in objects , Including mathematical objects Math、 Date object Date、 Array objects Array And string objects String etc. . Mastering the use of common built-in objects will bring great convenience to program development .

5.2.1_ Familiarize yourself with built-in objects by consulting the documentation

The objects explained earlier are objects written by developers themselves . For the convenience of program development ,JavaScript There are also many built-in objects , Many common development requirements can be accomplished using built-in objects , for example , Mathematical calculation 、 Date processing , Array operation, etc . For most developers , You don't have to spend time studying how these built-in objects are implemented , It is important to quickly master the use of built-in objects , So as to quickly put into development work .

because JavaScript There are many built-in objects provided , There are also version updates 、 Browser compatibility and other reasons , Therefore, the best way to learn about built-in objects is to consult the latest documents on the network .

So let's start with Mozilla Developer Network (MDN ) For example , Show me how to view JavaScript Use of built-in objects in :

  • open MDN Website , Find... In the navigation bar of the website “ technology ” —— "JavaScript,

  • Scroll the page down , You can find... In the left sidebar “ Built-in objects ” term , Expand the item , You can see the directory links of all built-in objects ,

  • in addition , If you don't know the name of the object , You can also enter keywords in the search box of the page to search , Find an object or method related to a keyword .

When learning the use of a method through documentation , Basically, it can be divided into 4 A step ,
For example, look up Math.max(), As follows :

  1. Look up Function of method . There is a... At the top of the page Paragraph text :“Math max0 Function returns the maximum value of a set of numbers .”. This passage is to introduce the function of the method .

  2. see Parameters The meaning and type of . It is known from the document that ,max() The parameters of the method are a set of values , Any amounts . In the syntax of the document , Use “[ ]” The parameters of the package represent optional parameters , It can be omitted .

  3. see Return value The meaning and type of . You can see specific instructions in the document .

  4. Test with sample code . Sample code is provided in the pages of most common methods in the document , You can learn how to use this method through sample code .

5.2.2_[ Case study ] Encapsulate your own mathematical objects

When the built-in object cannot meet the requirements , We can also encapsulate an object ourselves , To complete the specific operation . Next, we encapsulate a mathematical object myMath, To find the maximum value in the array ,

The specific code is as follows :

var myMath = {
    

pI: 3.141592653589793,

max: function() (

var max = arguments[0];uments. length; 1++){
    

for (var 1- 1; i < arguments

if (arguments[i] > max)

max = arguments[i];

return max;

}

console.log (myMath.PI);

/ Output results :3.141592653589793

console. log (myMath.max(10,20,30));

// Output results : 30

In the above code , The first 1 Line of code defines a myMah object . The first 2 Line of code sets PI Value . The first 3~ 11 Line of code defines a max Method , And make use of arguments To receive the input parameters , Returns the maximum value of the array . The first 13 Line code call myMahPI Get a defined value . The first 14 Line code call myMath.max() Method to get the maximum value in the array .

5.3_Math object

5.3.1_Math Use of objects

Math Object is used to perform mathematical operations on numbers , The object is not a constructor , There is no need to instantiate the object , You can use its static properties and static methods directly .

Math Common properties and methods of objects

member effect
PI Get the pi , The result is 3.141592653589793
abs(x) obtain x The absolute value of , You can pass in a normal value or a value represented by a string
max([value1[,value2,…]]) Get the maximum value of all parameters
min([value1[,value2,…]]) Get the minimum value of all parameters
pow(base, exponent) Get cardinality (base) The index of (exponent) The next power , namely base^exponent
sqrt(x) obtain x The square root of
ceil(x) Gets a value greater than or equal to x Minimum integer of , That is, round up
floor(x) Get less than or equal to x Maximum number of senses , I.e. round down
round(x) obtain x The rounded integer value of
random() Gets a value greater than or equal to 0.0 And less than 1.0 The random value

Case study :

Math.PI;//  Get the pi 
Math.abs(-25);//  Get absolute value , Return results :25
Math.abs('-25');//  Get absolute value , Automatically convert to digital , Return results :25
Math.max(5, 7, 9, 8);//  Get the maximum , Return results :9
Math.min(6, 2, 5, 3);//  Get the minimum , Return results :2
Math.pow(2, 4);//  obtain 2 Of 4 The next power , Return results :16
Math.sqrt(9);// obtain 9 The square root of , The return result is :3
Math.ceil(1.1);//  Rounding up , Return results : 2
Math.ceil(1.9);//  Rounding up , Return results :2
Math.floor(1.1);//  Rounding down , Return results :1
Math.floor(1.9);//  Rounding down , Return results :1
Math.round(1.1);//  rounding , Return results : 1
Math.round(1.5);//  rounding , Return results :2
Math.round(1.9);//  rounding , Return results :2
Math.round(-1.5);//  rounding , Return results :-1( Take the larger value )
Math.round(-1.6);//  rounding , Return results :-2

5.3.2_ Generate random numbers for a specified range

Math.random() Used to get random numbers , Each call to this method returns a different result . The result of this method is a very long floating point number , Such as “0.925045617789475 Its scope is 0~1( barring 1).

because Math.random() The random number returned is not commonly used , We can use some mathematical formulas to convert into random numbers in any range , Formula for “Math.random() * (max - min) + min", Indicates that the generation is greater than or equal to min And less than max The random value .

The sample code is as follows :

Math.random() * (3 - 1) + 1;  // 1 ≤  Return results  < 3
Math.random() * (20 - 10) + 10; // 10 ≤  Return results  < 20
Math.random() * (99 - 88) + 88; // 88 ≤  Return results  < 99

The return result of the above code is a floating point number , When you need to get integer results , Collocation Math.floor() To achieve .

Case study : Demonstrate how to get 1 ~ 3 Random integers in range , The return result may be 1、2 or 3:

function getRandom (min, max) {
    
return Math.floor(Math.random()*(max - min + 1) + min);
}
console.log(getRandom(1, 3)); //  minimum value 1, Maximum 3

In the above code , The first 2 Lines are used to generate min To max Random integer between , contain min and max. in addition , You can also use Math.floor (Math.random() * (max + 1)) To generate 0 To max Random integer between , Use Math.floor (Math.random() * (max + 1)+ 1) To generate 1 To max Random integer between .

Using random numbers , You can get a random element in the array , The sample code is as follows :

var arr = ['apple', 'banana', 'orange', 'pear'];
// Call the previously written getRandom() Function to get a random number 
console.log( arr[getRandom(0, arr.length-1)] );

5.3.3_[ Case study ] Guess the number game

Case study : demonstration Math Use of objects . Make the program generate a random 1 ~ 10 Number between 、 And let the user input a number, and the user input the number , Judge the size of these two numbers , If the number entered by the user is greater than the random number , So tips “ You guessed big ”, If the number entered by the user is less than a random number , Prompt “ You guess it's small ”, If two numbers are equal , Prompt “ congratulations , Guessed it ”, End procedure .

Case study :

function getRandom(min, max){
    
return Math.floor(Math.random() * (max - min + 1) + min);
} // Defined getRandom() function , utilize Math.random() Methods find random numbers .

var random = getRandom(1, 10);  // Set the random number size to 1~10 Number between 
while(true){
      // Dead cycle , Use the 13 Yes break To jump out of the loop 
var num = prompt(' Guess the number , The scope is 1~10 Between .');
if(num > random){
    
alert(' You guessed big ');
}else if(num < random){
    
alert(' You guess it's small ');
}else{
    
alert(' congratulations , Guessed it ');
break;// utilize while Use... In loop statements if...else if Multiple branch statements to determine greater than 、 Less than 、 be equal to 
}
}

5.4_ Date object

JavaScript The date object in is used to process date and time . for example , Real time display of date in second kill activity 、 Clock effect 、 Online calendar, etc .

5.4.1_ Use of date objects

JavaScript The date object in needs to use new Date() Only instantiated objects can be used ,Date() Is the constructor of the date object . When creating a date object , It can be for Date() The constructor passes in some parameters , To indicate a specific date , It is created as follows .

//  The way 1:  No parameters , Use the current time of the current system as the time when the object is saved 
var datel = new Date();
//  Output results : Wed 0ct 16 2019 10:57:56 GMT+0800 ( China standard time )
console.log (datel);

//  The way 2:  Heirloom year , month , Japan 、 when 、 branch 、 second ( The range of the month is 0 ~ 11, The real month -1)
var date2 = new Date(2019, 10, 16, 10, 57, 56);
//  Output results : Sat Nov 16 2019 10:57:56 GMT+0800 ( China standard time )
console.log(date2);

//  The way 3:  Use a string to represent the date and time 
var date3 = new Date('2019-10-16-10:57:56');
//  Output results : Wed Oct 16 2019 10:57:56 GMT+0800( China standard time )
console.log(date3);

In the way of use 1 when , It returned date1 The object is saved at the time when the object was created ;
In the way of use 2 when , At least a specified year is required 、 Two parameters of the month , Later parameters will automatically use default values when omitted ;
In the way of use 3 when , At least the year must be specified . in addition , When the value passed in is greater than a reasonable range , It will be automatically converted to adjacent values ( Such as way 2 Set month to -1 Last year 12 month , Set to 12 It means next year 1 month ).

After getting the date object , The direct output object gets a string representing the date and time . If you want to represent this date and time in other formats , This can be achieved by calling the relevant methods of the date object . The common methods of date objects are divided into get and set Two categories: .

Date Common use of objects get Method :

Method effect
getFullYear() Gets the... That represents the year 4 Digit number , Such as 2020
getMonth() Get month , The scope is 0 ~ 11(0 Means January ,1 It means February , By analogy )
getDate() Get a day in the month , Range 1 ~ 31
getDay() Get week , The scope is 0 ~ 6(0 Means Sunday ,1 For Monday , By analogy )
getHours() Get hours , The scope is 0 ~ 23
getMinutes() Get minutes , The scope is 0 ~ 59
getSeconds() Get seconds , The scope is 0 ~ 59
getMilliseconds() Get milliseconds , The scope is 0 ~ 999
getTime() Get from 1970-01-01 00:00:00 distance Date Object represents the number of milliseconds of time

Date Common use of objects set Method :

Method effect
setFullYear(value) Set year
setMonth(value) Set month
setDate(value) Set a day in the month
setHours(value) Set the hours
setMinutes(value) Set minutes
setSeconds(value) Set seconds
setMillseconds(value) Set the number of seconds
setTime(value) By getting from 1970-01-01 00:00:00 Set the time in milliseconds

Case study : Output the current date in the console .

var date = new Date();// Create... Based on the current date and time Date object 
var year = date.getFullYear();// Year of acquisition 
var month = date.getMonth();//  Get the month 
var day = date.getDate();// Acquisition date 
// Convert the week value into a string through an array 
var week =[' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday '];
// Output date The time the object was saved ,  Example : It's today 2019 year 9 month 16 Wednesday, Sunday ,
console.log(' It's today '+ year + ' year ' + month + ' month ' + day + ' Japan ' + week[date.getDay()]);

In the above code ,week[ date.getDay() ] Used to from date Object to get the week value , Then as an index of values to week Get the corresponding week string from the array .

Case study : Converts the time in the date object to the specified format ,

// Return current time , The format is : when : branch : second , Use two digits to represent 
function getTime(){
    

var time = new Date();
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() ); //  Example of output results : 10:07:56

In the above code , The first 5、7、 9 A line of code is used to determine whether a given number is a single digit , If it is a single digit, add “0”.

5.4.2_[ Case study ] Statistics code execution time

The date object allows you to get data from 1970 year 1 month 1 Japan 0 when 0 branch 0 Seconds to the present UTC The number of milliseconds elapsed in time , This value can be used as a timestamp . By time stamping , You can calculate the time difference between two times , It can also be used to encrypt 、 Digital signature and other technologies .

The common ways to obtain time stamps are as follows :

// The way 1: Through the... Of the date object valueof() or getTime() Method 
var datel = new Date();
console.log( datel.valueOf() );
//  Sample results : 1571196996188
console.log( datel.getTime() );
//  Sample results : 1571196996188

// The way 2: Use "+" Operator to numeric type 
var date2 = +new Date();
console.log(date2);
//  Sample results : 1571196996190

//  The way 3: Use HIMLS Newly added  Date.now() Method 
console.log( Date.now() );
//  Sample results : 1571196996190

 Insert picture description here

After mastering how to get the timestamp , Let's finish the coding of the case , The specific code is as follows .

var timestamp1 = +new Date();

for(var i = 1, str = ''; i <= 90000; i++){
    
str += i;
}

var timestamp2 = +new Date();
//  Sample results : Code execution time : 37 millisecond 
console.log(' Code execution time :' + (timestamp2 - timestamp1) + ' millisecond ');

As can be seen from the above code and output example ,JavaScript For string variables str the 90000 Secondary splicing operation , It costs 37 Execution time in milliseconds . The time will vary according to the operation speed of different computers .

5.4.3_[ Case study ] count down

The countdown mark of discounted goods often appears on the activity page of some e-commerce websites , Shows that... Is left until the end of the activity X God X Hours X branch X second , A countdown like this can be implemented using a date object .

The core algorithm of the countdown is the input time minus the current time , The remaining time obtained is the countdown time to be displayed . This requires converting the time into a timestamp ( Number of milliseconds ) To calculate , Convert the number of milliseconds obtained into days 、 Hours 、 fraction 、 Number of seconds .

The specific example code is as follows :

function countDown(time){
    
var nowTime = +new Date();
//+new Date()  yes new Date().getTime()  Code abbreviation , Returns the current timestamp , In milliseconds .
var inputTime = +new Date(time);
// Set the end timestamp of the activity .
var times  = (inputTime - nowTime) / 1000;
// Calculate the number of milliseconds remaining , Need to convert to seconds , The conversion rule is 1 second /1000 millisecond .
var d = parseInt(times / 60 / 60 / 24);
d = d < 10 ? '0' + d : d;
var h = parseInt (times / 60 / 60 % 24);
h = h < 10 ? '0' + h : h;
var m = parseInt(times / 60 % 60);
m = m < 10 ? '0' + m : m;
var s = parseInt(times % 60);
s = s < 10 ? '0' + s : s;
return d + ' God ' + h + ' when ' + m + ' branch ' + s + ' second ';
//  The first 5 ~ 13  Line code calculation days d、 Hours h、 time-sharing m、 Number of seconds s,  And use returm return .
}
//  Sample results : 05 God 23 when 06 branch 10 second 
console.log(countDown('2019-10-22 10:56:57'));
//  The output distance specifies the end date 2019-10-22 10:56.57 How much time is left .

5.5_ Array objects

JavaScript Array objects in can use new Array Or literally “[ ]” To create .

5.5.1_ Array type detection

In development , Sometimes you need to check whether the type of the variable is an array . for example , In two numbers . The required parameters must be an array , You cannot pass in other types of values , Otherwise it will go wrong , So at this time, you can check whether the type of parameter is array in the function . There are two common ways to detect array types , They are using instanceof Operators and use Array.isArray() Method .

The sample code is as follows :

var arr = [];
var obj = {
     };
//  The first 1 Ways of planting 
console.log ( arr instanceof Array );
//  Output results :true
console.log ( obj instanceof Array );
//  Output results :false
// The first 2 Ways of planting 
console.log ( Array.isArray(arr) );
//  Output results :true
console.log ( Array.isArray(obj) );
//  Output results :false

In the above code , If the test result is true, Indicates that the given variable is an array , If the test result is false, Indicates that the given variable is not an array .

5.5.2_ Add or remove array elements

JavaScript Array objects provide methods to add or remove elements , You can add a new array element at the end or beginning of the array , Or move out array elements at the end or beginning of the array .

Add or remove array elements :

Method name Function description Return value
push( Parameters 1… ) Add one or more elements to the end of the array , The original array will be modified Returns the new length of the array
unshift( Parameters 1… ) Add one or more elements to the beginning of the array , The original array will be modified Returns the new length of the array
pop() Delete the last element of the array , If it is an empty array, it returns undefined, The original array will be modified Returns the value of the deleted element
shift() Deletes the first element of the array , If it is an empty array, it returns undefined, The original array will be modified Returns the value of the first element

It should be noted that ,push() and unshift() Method is the length of the new array , and pop() and shift() Method returns the removed array elements .

Case study : demonstration

<script>
var arr = ['Rose', 'Lily'];
console.log(' Original array :'+ arr);
var last = arr.pop();
console.log(' Remove the element at the end :'+ last + '-  After removal, the array :' + arr);
var len = arr.push('Tulip', 'Jasmine');
console.log(' After adding an element at the end, the length becomes :'+ len + '-  After adding the array :'+ arr);
var first = arr.shift();
console.log(' Remove the element at the beginning :'+ first + ' -  After removal, the array :' + arr);
len = arr.unshift('Balsam', 'sunflower');
console.log(' After adding an element at the beginning, the length becomes :' + len + '-  After adding the array :' + arr);
</script>

 Insert picture description here

As can be seen from the above code ,push() and unshift() Method can add one or more elements at the end or beginning of the specified array , and pop() and shift() Method can only move out and return an element of the specified array that is not at the end or beginning .

5.5.3_[ Case study ] Filter array

Case study : It is required to be in the array containing salary , Excluding wages, reach 2000 Or above , The less than 2000 Put the number back into the innovative array . Where the array is [1500,1200,2000, 2100, 1800].

var arr = (1500, 1200, 2000, 2100, 1800];
var newArr = [];

for (var i = 0; i < arr.length; i++) {
    
if (arr[i] < 2000) {
    
newArr.push(arr[1);
//  amount to : newArr (newArr.length] = arr[i];
}
}

console.log(newArr);
//  Output results : (3) [1500, 1200, 1800]

In the above code , The first 1 The line code is the original array arr. The first 2 This line of code defines the new array newArr, The deposit salary is lower than 2000 The data of . The first 3 Lines of code in for Pass... In a loop statement if Sentence to judge , If it meets the requirements, use push() Method , Store in new array newArr in .

5.5.4_ Array sorting

Array sorting can sort array elements or reverse the order of array elements .

Sorting method :

Method name Function description
reverse() Reverse the position of elements in an array , 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

It should be noted that ,reverse() and sort() Method is the length of the new array .

// Inversion array 
var arr = ['red', 'green', 'blue'];
arr.reverse();
console.log(arr);// Output results :(3) ["blue", "green","red"]
// The above demonstrates  reverse()  Use of methods , Implement the inversion of array elements .
// Array sorting 
var arr1 = [13, 4, 77, 1, 7];
arrl.sort(function(a, b) 
return b - a;// In descending order 
});
console.log(arr1);// Output results : (5) [77,13,7,4,1]
// The above demonstrates  sort()  Use of methods , Sort the array elements from large to small .

 Insert picture description here

return a - b;//  In ascending order 

 Insert picture description here

5.5.5_ Array index

In development , To find the position of the specified element in the array , You can use Array Object .

Search method :

Method name Function description
indexOf() Returns the first index of the given value that can be found in the array , If it doesn't exist , Then return to -1
lastIndexOf() Returns the index of the last specified element in the array , Returns if it does not exist -1

In the above methods , By default, the retrieval starts from the position of the specified array index , And the retrieval method is the same as the operator " === " identical , That is, only congruent will return a more successful result .

Case study : demonstration ,

var arr = ['red', 'green', 'blue', 'pink', 'blue'];
console.log( arr.indexOf('blue') );    // Output results :2
console.log( arr.lastIndexOf('blue') );// Output results :4

In the above code ,lastIndexOf() Method to retrieve the subscript of the last given value from the specified subscript position in the array . And indexOf() The different way of searching is ,lastIndexOf() Method defaults to reverse retrieval , That is, retrieve... From the end of the array to the beginning of the array .

5.5.6_[ Case study ] Array to remove duplicate elements

Next, we use a case to demonstrate the use of array index . Require in a set of data , Remove repetitive elements . Where the array is [‘blue’, ‘green’, ‘blue’] . The sample code is as follows .

function unique(arr) {
    
var newArr = [];
//  Used to store non repeating elements in the array 

//  Go through the array , If an element in the array appears repeatedly, it is put into the new array 
for(var i = 0; i < arr.length; i++) {
    
if(newArr.indexOf(arr[i]) == -1) {
    
newArr.push(arr[i]);
}
}

return newArr;
}

var demo = unique(['blue', 'green', 'blue']);
console.log(demo);
//  Output results : (4) ["blue","green"]

There have been , Then add it to the new array , Otherwise, do not add . Among them the first 4 Line of code if the element determines if the return value is -1 It means that there is no element in the new array .

3 Using the new array, there is no... In the new array

5.5.7_ Array to string

If you need to convert an array to a string , You can use the of array objects join() and toString() Method realization .

Array to string :

Method name Function description
toString() Convert an array to a string , Comma separated each item
join (’ Separator ') Concatenate all elements of the array into a string

Case study : demonstration ,

//  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 results :abc
console.log ( arr.join('-') );
//  Output results :a-b-c

 Insert picture description here

From the above code, we can see ,join() and toString() Method to convert a multidimensional array into a string , Comma concatenation is used by default . The difference is ,join() Method can specify the symbol to connect array elements . in addition , When the array element is undefined、null Or an empty array , The corresponding element will be converted to an empty string .

5.5.8_ Other methods

JavaScript It also provides many other commonly used array methods . for example , Fill the array 、 Linked array 、 Intercept array elements, etc .

Other methods :

Method name Function description
fill() Fills all elements within the specified subscript range in the array with a fixed value
splice() Array delete , Parameter is splice( The first few starts , To delete the number of ), Returns a new array of deleted items
slice() Array truncation , Parameter is slice(begin, end), Returns a new array of intercepted items
concat() Connect two or more arrays , Does not affect the original array , Returns a new array

slice() and concat() Method returns a new array after execution , Does not affect the original array , The remaining methods will affect the original array after execution .

Case study :splice() Method to add or delete array elements at the specified location ,

var arr = ['sky', 'wind', 'snow', 'sun'];
//  From index to 2 The position begins , Delete 2 A dollar 
arr.splice(2, 2);
console.log (arr); 
//  Output results : (2) ["sky", "wind"]

//  From index to 1 The position begins , Delete 1 After elements , Add again  snow  Elements 
arr.splice(1, 1, 'snow');
//  Output results : (2) ["sky", "snow"]
console.log(arr);

//  From index to 1 The position begins , Add array elements 
arr.splice(1.0, 'hail', 'sun');
console.log(arr);
//  Output results : (4) ["sky", "hail", "sun", "snow"]

In the above code ,splice() Methods the first 1 Two parameters are used to specify the subscript position to add or remove ; The first 2 Parameters are used to start at the specified subscript position , Delete the number of array elements , Set it to 0, It means that the method only adds elements ; The remaining parameters represent the array elements to be added , If omitted, it means to delete the element .

5.6_ String object

stay JavaScript in , String objects provide properties and methods for processing strings , You can easily find strings 、 Intercept 、 Replace 、 Case conversion and other operations .

5.6.1_ Use of string objects

String objects use new String() To create , stay String Pass in the string in the constructor , The string will be saved in the returned string object .

Case study : demonstration ,

// Create string object 
var str = new string('apple');
//  Create string object 
console.log (str);
//  Output results : string{"apple"}

//  Get string length , Output results :5
console.log(str.length);

Careful readers will find out , In the previous study , have access to “ String variable .length " How to get , This approach is much like accessing an object length attribute .

Case study : demonstration ,

var str = 'apple';
console.log (str.length);
//  Output results : 5

actually , The string is in JavaScript Is a basic type of packaging .JavaScript The basic packaging types in include String、Number and Boolean , Used to wrap basic data types into complex data types , Thus, the basic data type also has properties and methods .

It should be noted that , although Javascript The mechanism of basic wrapper types enables ordinary variables to access properties and methods like objects , But they are not object types .

Case study : demonstration ,

var obj = new String('Hello');
console.log (typeof obj); 
//  Output results : object

console.log (obj instanceof String); 
// Output results : true

var str = 'Hello';
console.log (typeof str); 
//  Output results : string

console.log (str instanceof String); 
//  Output results : false

 Insert picture description here

As can be seen from the above code , Use new String() Back to obj It's an object , But an ordinary string variable is not an object , It's just a string of data .

5.6.2_ Return position according to character

String objects provide properties and methods for retrieving elements

String objects are used to retrieve the properties and methods of elements

member effect
indexOf( search Value ) obtain search Value The first occurrence in a string
lastIndexOf( search Value ) obtain search Value The last position in the string

Case study : demonstration indexOf() and lastIndexOf() Use of methods ,

var str = 'HelloWorld' ;

console.log( str.indexOf('o') );
//  obtain "o" The first occurrence in a string , Return results :4
console.log( str.lastIndexOf('o')  );
//  obtain "o" The last position in the string , Return results :6

 Insert picture description here

You can see from the returned results , Location slave 0 Start calculating , The position of the first character of the string is 0 , The first 2 The characters are 1, And so on , The position of the last character is the length of the string minus 1.

Case study : In a set of strings , Find the location and number of occurrences of all specified elements . String is ’ Hello World, Hello JavaScript ’ .

var str = 'Hello World,Hello Javascript';
var index = str.indexOf('o'); //  Find the first one  o  Position of appearance .
var num = 0; //  Set up  o  The initial value of the number of occurrences is 0.
while(index != -1){
      //  adopt  while  Sentence judgment  indexOf  The result of the return value 
// If not -1 Just keep looking back , This is because  indexOf  Only the... Can be found 1 individual ,
// Therefore, the following search needs to use the second 2 Two parameters to implement , Give the current index  index  Add 1,
// So as to continue to find .
console.log (index);//  Output... In sequence :4、7、17
index = str.indexOf('o', index + 1);
num++;
}
console.log ('o The number of times is :' + num);// o  The number of times is :3

It should be noted that , Spaces in strings are also treated as one character .

5.6.3_ Returns the character according to the position

stay JavaScript in , The string object provides a method for obtaining a character in a string .

String object is the method used to get a character

member effect
charAt(index) obtain index The character of position , Location slave 0 Start calculating
charCodeAt(index) obtain index The character of the position ASCII code
str [ index ] Gets the character at the specified position ( HTML5 newly added )

Case study : understand charAt()、charCodeAt()、str[ Subscript ] Use ,

var str = 'Apple';
console.log (str.charAt(3));//  Output results :1
console.log (str.charCodeAt(0));//  Output results : 65( character A Of  ASCII  Code for 65)
console.log(str[0]);//  Output results :A

5.6.4_[ Case study ] Count the most characters and times

Case study : demonstration charAt() Use of methods . Through the program to count the most characters and times in the string

var str = 'Apple';
// The first 1 Step   Count the number of occurrences of each character 
var o = {
     };

for (var i = 0; i < str.length; i++) {
    
var chars = str.charAt(i); 
//  utilize  chars  Save every character in the string 
if( o[chars] ) {
       
//  Use the attributes of the object to facilitate the search of elements 
o[chars]++;
}else{
    
o[chars] = 1;
}
}

console.log(o); //  Output results :{A: 1, p: 2, 1:1,e:1}

var max = 0;    //  Save the maximum number of occurrences 
var ch = '';    //  Save the most frequent characters 

for(var k in o){
    
if (o[k] > max){
    
max = o[k];
ch = k;
}
}

//  Output results :" The most common characters are :p, A total of the 2 Time "
console.log(' The most common characters are :' + ch + ', A total of the ' + max + ' Time ');

 Insert picture description here

5.6.5_ String operation method

String objects provide some for intercepting strings 、 Connection string 、 Replace the properties and methods of the string

The string object is used to intercept 、 Methods of connecting and replacing strings

member effect
concat(strl, str2, str3…) Concatenate multiple strings
slice(start,[ end ]) Interception from start Position to end A substring between positions
substring(start [,end] ) Interception from start Position to end A substring between positions , Basic and slice identical , But don't accept negative values
substr(start [, length] ) Interception from start Position start to length Substring of length
toLowerCase() Gets the lowercase form of the string
toUpperfCase() Gets the uppercase form of the string
split( [ sparator [, limit] ) Use separator Delimiters separate strings into arrays ,limit Used to limit the number of
replace(str1, str2) Use str2 Replace in string str1 , Return the replacement result , Only the first character will be replaced

When using the methods in the above table to operate on a string , The processing result is returned directly through the return value of the method , It doesn't change the string itself .

Case study : demonstration ,

var str = 'HelloWorld';
str.concat('!');     //  Splice characters at the end of the string , result :HelloWorld!
str.slice(1, 3);     //  Intercept from location 1  Start to position 3  Content in scope , result :el
str.substring (5);  //  Intercept from location 5  From the beginning to the end , result : World
str.substring(5, 7);  //  Intercept from location 5  Start to position 7  Content in scope , result :Wo
str.substr(5);      //  Intercept from location 5  From the beginning to the end of the string , result : World
str.substring(5, 7);//  Intercept from location 5  Start to position 7  Content in scope , result :Wo
str.toLowerCase();  //  Convert string to lowercase , result :helloworld
str.toUpperCase();  //  Convert strings to uppercase , result :HELLOWORLD
str.split('1');    //  Use "1" Cut string , result :["He","","oWor","d"]
str.split('1', 3);  //  Limit the maximum number of cuts 3 Time , result :["He","","oWor"]
str.replace('World','!');//  Replace string , result :"Hello!"

5.6.6_[ Case study ] Judge whether the user name is legal

Case study : The length of the user name is required to be 3 ~ 10 Within the scope of , Sensitive words are not allowed admin In any case .

var name = prompt(' Please enter the user name ');
if (name.length < 3 || name.length > 10){
    
alert(' The length of the user name must be in 3 ~ 10 Between .');
} else if (name.toLowerCase().indexOf('admin') !== -1){
    
alert(' The user name cannot contain sensitive words : admin.');
}else{
    
alert(' Congratulations , The user name can be used ');
}

The above code is judged by length Property to verify the length of the user name ; By converting the user name to lowercase, find out whether it contains sensitive words admin . The implementation name Convert to lowercase before searching , You can use the account name regardless of the case combination , Can check out .indexOf() Method returns... When the lookup fails -1, Therefore, judging the return value of the method can know whether the user name contains sensitive words .

5.7_ Value type and reference type

stay JavaScript in , Basic data type ( Such as string type 、 Digital 、 Boolean type 、undefined、null ) Also known as value type , Complex data type ( object ) Also known as reference type . The characteristics of reference types are , What is stored in the variable is only the address of a reference , When assigning a value to a variable , Instead of copying an object , Instead, point two variables to a reference to the same object .

Case study : for example , In the following code obj1 and obj2 Pointed to the same object .

// Create an object , And through variables  obj1  Save references to objects 
var obj1 = {
    name:' Xiao Ming ', age:18};
//  There are no copied objects at this time , It is  obj2  and  obj1  Two variables refer to the same object 

var obj2 = objl;
//  Compare whether two variables refer to the same object 
console.log (obj2 == obj1); //  Output results :true
//  adopt  obj2  Modify the properties of an object 
obj2.name = ' Xiaohong ';
//  adopt  obj1  Visit the target  name  attribute 
console.log (obj1.name) //  Output results : Xiaohong 

After the above code is executed ,obj1 and obj2 Two variables refer to the same object , here , Whether to use obj1 The operation object still uses obj2 Action object , The actual operation is the same object .

When obj1 and obj2 After two variables point to the same object , If you give one of the variables ( Such as obj1 ) Reassign to other objects , Or reassign it to another value , be obj1 The original object will no longer be referenced , but obj2 Still referring to the original object .

Case study : Demonstrate the above Overview :

var objl = name:' Xiao Ming ', age: 18 };
var obj2 = objl;
// obj1  Points to a newly created object 
obj1 = {
     name: ' Xiaohong ', age: 17 };
// obj2  Still point to the original object 
console.log (obj2.name); // Output results : Xiao Ming 

In the above code , The first 1 Lines of code name For Xiao Ming's object , At the beginning, there was only obj1 quote , In the implementation of the 2 After line code ,obj1 and obj2 All reference this object , Execution section 4 After line code , Only obj2 Reference the object . When an object is referenced by only one variable , If this variable is reassigned , Then the object will become a case without any variable references , At this time, it will be JavaScript The garbage collection mechanism automatically releases .

When a variable of reference type is passed as a parameter of a function , The effect is similar to the assignment between variables . If you modify the properties or methods of an object in the parameters of a function , The result accessed by referencing the variable of this object outside the function is also modified .

Case study : Demonstrate the above Overview ,

function change(obj){
    
obj.name = ' Xiaohong '; //  Modified the properties of the object in the function 
}
var stu = {
     name:' Xiao Ming ', age: 18 };
change(stu);
console.log (stu.name); //  Output results : Xiaohong 

In the above code , When calling change() After the function , stay chang() Function obj.name Value . After modification , More than... Outside the function stu The result of variable access is the modified value , Explanatory variable stu And parameters obj It refers to the same object .

Today's introductory study has come to an end
Peace

Looking back :

JavaScript Study :
Challenge to get you started in the shortest time JavaScript( One )
Challenge to get you started in the shortest time JavaScript( Two )
Challenge to get you started in the shortest time JavaScript( 3、 ... and )
Challenge to get you started in the shortest time JavaScript( Four )
HTML Study :
o ken Of HTML、CSS Learning notes of _HTML Basics ( Note 1 )
o ken Of HTML、CSS Learning notes of _HTML Page elements and attributes ( Note 2 )
o ken Of HTML、CSS Learning notes of _ Text style properties ( Note 3 )
o ken Of HTML、CSS Learning notes of _CSS3 Selectors ( Note 4 )
o ken Of HTML、CSS Learning notes of _CSS Box model ( Note 5 )
o ken Of HTML、CSS Learning notes of _ Floating and positioning ( Note 6 )
o ken Of HTML、CSS Learning notes of _ Application of forms ( Note 7 )
o ken Of HTML、CSS Learning notes of _ Multimedia technology ( Note 8 )
o ken Of HTML、CSS Learning notes of _CSS3 Advanced applications ( Note 9 )

About postscript :

Thank you for reading , I hope it helped you If the blog is flawed, please leave a message in the comment area or add contact information in the personal introduction of the home page to chat with me Thank you for your advice
Originality is not easy. ,「 give the thumbs-up 」+「 Focus on 」+「 Collection 」 Thank you for your support

copyright notice
author[Please call me Ken],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827022712104p.html

Random recommended