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

Posted by phpQuestioner on Fri, 24 Dec 2021 08:20:12 +0100

Thank you for meeting. Hello, I'm ken

Author: please call me ken
Link: Please call me a ken home page link
Source: CSDN
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.

🌊🌈 About Preface:

Some of the contents and pictures are from the Internet. If there are any questions, please contact me official account.
This blog is temporarily applicable to those who have just come into contact with HTML and want to review for a long time.

🌊🌈 About content:

JavaScript object

5.1_ Initial object

5.1. 1_ What is an object

For example, if a mobile phone object is described in JavaScript, the properties and methods of the mobile phone are as follows:

  • Phone properties: color, weight, screen size.
  • Methods of mobile phone: making phone calls, sending text messages, watching videos and listening to music.
    In the code, the attribute can be regarded as a variable saved in the object, which is represented by "object. Attribute name"; Method can be regarded as a function saved in the object and accessed with "object. Method name ()".
// Suppose there is a mobile phone object p1, which is 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 + 'Send a text message to:' + message);
},

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

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

};

//Accessing properties of p1
console.log (pl.color);     // Output result: "black", indicating that the color of the mobile phone is black
console.log (p1.weight);    // Output result: "188g", indicating that the weight of the mobile phone is 188g
console.log (p1.screenSize);// Output result: "6.5", indicating that the screen size of the mobile phone is 6.5 inches

//Method calling p1
p1.call('123');           // Call the dialing method of the mobile phone, and the dialing number is 123
p1.sendMessage('123', 'hello'); // Send a text message to phone number 123 with the content of 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, the use methods of object attributes and variables are similar, and the use methods of object methods and functions are similar.
Through the object, a series of attributes and methods can be collected and represented by a simple variable name p1.

5.1. 2_ Creating objects with literals

In JavaScript, the literal value of an object is to wrap the members in the object with curly brackets "{". Each member is saved in the form of "key: value". Key represents the property name or method name, and value represents the corresponding value. Multiple object members are separated by ",".

Case:

// 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 with no members. stu1 object contains four members: name, age, sex and sayHello, where name, age and sex are attribute members and sayHello is method member.

5.1. 3_ Access the properties and methods of the object

After the object is created, you can access the properties and methods of the object.
The example code is as follows:

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

//Call the method of the object (syntax 1)
stul.sayHello();        // Output result: Hello
//Call the method of the object (syntax 2)
stul['sayHello']();     // Output result: Hello 

If the member name of an object contains special characters, it can be represented by a string,
The example code is as follows:

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

JavaScript objects have 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 the name attribute to the object
stu2.introduce = function() {     // Add the introduce method to the object
alert ('My name is ' + this.name);// Use this to represent the current object in the method
};

alert (stu2.name);//Access the name attribute and output the result: Jack
stu2.introduce();//Call the introduce() method and output the result: My name is Jack

In the above code, this can be used to represent the object itself in the method of the object. Therefore, use this Name can access the name attribute of the object.

undefined is returned when accessing a property that does not exist in the object.
The example code is as follows:

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

5.1. 4_ Creating objects with new objects

When we learned about arrays earlier, we know that we can use new Array to create array objects. Array is a special object. If you want to create an ordinary object, use new Object to create it.

The example code is as follows:

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

5.1. 5_ Creating objects with constructors

The literal method learned earlier is only suitable for creating one object. When you need to create multiple objects, you have to write each member of the object again, which is obviously troublesome. Therefore, you can use the constructor to create objects. The syntax of using the constructor to create an object is "new constructor name ()". Parameters can be passed to the constructor in parentheses. If there are no parameters, parentheses can be omitted.

In fact, "new Object()" is a way to create an object using a constructor. Object is the name of the constructor, but an empty object is created in this way.

The basic syntax is as follows:

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

//Creating objects using constructors
var obj = new Constructor name();

In the above syntax, this in the constructor 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 constructor name is recommended to be capitalized.

Case:

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

//Create an object using the Student constructor
var stul = new Student('Xiao Ming', 18);
console.log(stul.name);         // Output result: Xiao Ming
console.log(stu1.sayHello());   // Output result: Hello, my name is Xiao Ming
var stu2 = new Student('Xiao Hong', 17);
console.log(stu2.name);         // Output result: Xiaohong
console.log(stu2.sayHello());   // Output result: Hello, my name is Xiao Hong

Constructors in JavaScript are similar to classes in traditional object-oriented languages (such as Java), so some terms in object-oriented programming can also be used in JavaScript.

  • Abstraction: the process of extracting the common features of a class of objects and writing them into a construction function (class) is called abstraction.

  • Instantiation: the process of creating objects using constructors (classes) is called instantiation.

  • Instance: if the stu1 object is created by the Student constructor, the stu1 object is called an instance of the Student constructor (or instance object).

Tip:
In some documents, methods in objects are often called functions, or construction functions are called constructors or construction methods. We only need to understand that these names refer to the same thing.

Learn more: static members

There is the concept of static in object-oriented programming, and JavaScript is no exception. Static members in JavaScript refer to the properties and methods of the constructor itself, which can be used without creating an instance object.

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

function Student(){
}

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

console.log(Student.school);    //Output: x University
Student.sayHello();             //Output result: 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 example code is as follows:

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

// Traversing obj objects
for(var k in obj){
// Through k, you can get the property name or method name in the traversal process
console.log(k);        // Output name, age and sex in sequence
console.log (obj[k]);  // Output in sequence: Xiao Ming, 18, male
}

In the above code, K is a variable name, which can be customized. It is customarily named K or key, indicating the key name. When traversing each member, use K to get the name of the current member and obj[k] to get the corresponding value. In addition, if the object contains methods, they can be called through "obj[k] ()".

Learn more: judge whether the object member exists

When you need to judge whether a member in an object exists, you can use the in operator,
Case:

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

As can be seen from the above code, when the member of the object exists, it returns true, and when it does not exist, it returns false.

5.2_ Built in object

To facilitate program development, JavaScript provides many commonly used built-in objects, including Math object math, Date object date, Array object Array, String object 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. In order to facilitate program development, JavaScript also provides many built-in objects. Using built-in objects can complete many common development requirements, such as mathematical calculation, date processing, array operation, etc. For most developers, it is not necessary to spend time studying the implementation principle of these built-in objects. It is important to quickly master the use of built-in objects, so as to quickly put into development work.

Because there are many built-in objects provided by JavaScript, there are also various reasons such as version update and browser compatibility. Therefore, the best way to learn built-in objects is to consult the latest documents on the network.

Next, we take the Mozilla Developer Network (MDN) as an example to demonstrate how to check the use of built-in objects in JavaScript:

  • Open the MDN website and find "technology" - "JavaScript" in the navigation bar of the website,

  • Scroll down the page to find the "built-in objects" item in the left sidebar. After expanding the item, you can see the directory links of all built-in objects,

  • In addition, if you do not know the name of the object, you can also enter a keyword in the search box of the page to search and find the object or method related to a keyword.

When learning the use of a method through documents, it can be basically divided into four steps,
For example, look up math Max (), as follows:

  1. Refer to the function of the method. At the top of the page is a text: "the Math max0 function returns the maximum value in a set of numbers.". This passage is to introduce the function of the method.

  2. View the meaning and type of parameters. It can be seen from the document that the parameters of the max() method are a set of values, and the number is unlimited. In the syntax of the document, the parameters wrapped with "[]" represent optional parameters, which can be omitted.

  3. View the meaning and type of the return value. 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, through which you can learn how to use this method.

5.2. 2_ [case] encapsulate your own mathematical object

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

The specific codes are 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 result: 30

In the above code, line 1 defines a myMah object. Line 2 sets the value of PI. Lines 3 ~ 11 define a max method, and use arguments to receive the input parameters and return the maximum value of the array. Line 13 calls myMahPI to get the defined value. Line 14 calls mymath The max () method gets the maximum value in the array.

5.3_Math object

5.3. 1_ Use of math objects

Math object is used to perform math related operations on numbers. This object is not a constructor and does not need to instantiate an object. You can directly use its static properties and static methods.

Common properties and methods of Math objects

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

Case:

Math.PI;// Get pi
Math.abs(-25);// Get absolute value, return result: 25
Math.abs('-25');// Obtain the absolute value, automatically convert it to a number, and return the result: 25
Math.max(5, 7, 9, 8);// Get the maximum value and return the result: 9
Math.min(6, 2, 5, 3);// Get the minimum value and return the result: 2
Math.pow(2, 4);// Get the 4th power of 2 and return the result: 16
Math.sqrt(9);//Get the square root of 9, and the return result is: 3
Math.ceil(1.1);// Round up and return result: 2
Math.ceil(1.9);// Round up and return result: 2
Math.floor(1.1);// Round down and return result: 1
Math.floor(1.9);// Round down and return result: 1
Math.round(1.1);// Rounding, return result: 1
Math.round(1.5);// Rounding, return result: 2
Math.round(1.9);// Rounding, return result: 2
Math.round(-1.5);// Rounding, return result: - 1 (take the larger value)
Math.round(-1.6);// Rounding, return result: - 2

5.3. 2_ Generates a random number in the specified range

Math.random() is used to obtain random numbers, and the results returned by each call of this method are different. The result returned by this method is a very long floating-point number, such as "0.925045617789475", which ranges from 0 to 1 (excluding 1).

Because of math The random number returned by random() is not very common. We can convert it into random numbers in any range with the help of some mathematical formulas. The formula is "Math.random() * (max - min) + min", which means to generate random values greater than or equal to min and less than max.

The example code is as follows:

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

The return result of the above code is a floating point number. When you need to obtain an integer result, you can match math Floor ().

Case: demonstrate how to obtain random integers in the range of 1 ~ 3. The returned results may be 1, 2 or 3:

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

In the above code, the second line is used to generate a random integer between min and Max, including min and max. You can also use math Floor (math. Random() * (MAX + 1)) means generating a random integer between 0 and Max, using math Floor (math. Random() * (MAX + 1) + 1) means to generate a random integer between 1 and max.

Using random numbers, you can randomly obtain elements in the array. The example code is as follows:

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

5.3. 3_ [case] number guessing game

Case: demonstrate the use of Math objects. Make the program randomly generate a number between 1 and 10, and let the user input a number. The user input the number to judge the size of the two numbers. If the number entered by the user is greater than the random number, it will prompt "you guess big". If the number entered by the user is less than the random number, it will prompt "you guess small". If the two numbers are equal, it will prompt "Congratulations, you guessed right", End the program.

Case:

function getRandom(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
} //The getRandom() function is defined, using math Random () method to find the random number.

var random = getRandom(1, 10);  //Set the random number size between 1 and 10
while(true){  //Dead loop, use the break on line 13 to jump out of the loop
var num = prompt('Guess the number, in the range of 1~10 between.');
if(num > random){
alert('Guess it's too big');
}else if(num < random){
alert('Guess it's small');
}else{
alert('Congratulations, you guessed right');
break;//Using if in while loop statement Else if multiple branch statements to determine greater than, less than, or equal to
}
}

5.4_ Date object

Date objects in JavaScript are used to handle dates and times. For example, real-time display of date, clock effect, online calendar, etc.

5.4. 1_ Use of date objects

The date object in JavaScript can only be used by instantiating the object with new Date(), which is the constructor of the date object. When creating a date object, you can pass some parameters to the date () constructor to represent the specific date. Its creation method is as follows.

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

// Method 2: year, month, day, hour, minute and second (the range of month is 0 ~ 11, that is, the real month - 1)
var date2 = new Date(2019, 10, 16, 10, 57, 56);
// Output: Sat Nov 16 2019 10:57:56 GMT+0800 (China standard time)
console.log(date2);

// Method 3: use string to represent date and time
var date3 = new Date('2019-10-16-10:57:56');
// Output: wed OCT 16 2019 10:57:56 GMT + 0800 (China standard time)
console.log(date3);

When mode 1 is used, the date1 object returned is saved at the time when the object was created;
When using mode 2, you need to specify at least two parameters: year and month. The following parameters will automatically use the default value when omitted;
When using mode 3, you need to specify at least the year. In addition, when the incoming value is greater than a reasonable range, it will be automatically converted to adjacent values (for example, in mode 2, set the month to - 1 to indicate last December, and set it to 12 to indicate next January).

After the date object is obtained, the date and time represented by a string are obtained by directly outputting the object. If you want to represent the date and time in other formats, you can call the relevant methods of the date object. The common methods of date objects are divided into two categories: get and set.

Common get methods for Date objects:

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

Common set methods for Date objects:

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

Case: output the current date in the console.

var date = new Date();//Creates a Date object based on the current Date time
var year = date.getFullYear();//Acquisition year
var month = date.getMonth();// Get month
var day = date.getDate();//Acquisition day
//Converts the week value to a string through an array
var week =['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
//Output the saving time of the date object. Example: today is Wednesday, September 16, 2019,
console.log('Today is'+ year + 'year' + month + 'month' + day + 'day' + week[date.getDay()]);

In the above code, week [date. Getday()] is used to get the week value from the date object, and then use it as the index of the value to get the corresponding week string from the week array.

Case: convert the time in the date object to the specified format,

//Returns the current time in the format of: hour: minute: second, represented by two digits
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 result: 10:07:56

In the above code, lines 5, 7 and 9 are used to judge whether a given number is a single digit. If it is a single digit, add "0" before it.

5.4. 2_ [case] statistical code execution time

Through the date object, you can get the number of milliseconds from 0:0:0 on January 1, 1970 to the current UTC time. This value can be used as a timestamp. Through timestamp, the time difference between two times can be calculated. It can also be used in encryption, digital signature and other technologies.

Common ways to obtain time stamps are as follows:

//Method 1: through the valueof() or getTime() method of the date object
var datel = new Date();
console.log( datel.valueOf() );
// Example result: 1571119696188
console.log( datel.getTime() );
// Example result: 1571119696188

//Method 2: use "+" operator to convert to numeric type
var date2 = +new Date();
console.log(date2);
// Example result: 15711196996190

// Method 3: use the date added by HIMLS Now() method
console.log( Date.now() );
// Example result: 15711196996190

After mastering how to obtain the timestamp, let's complete 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();
// Example result: code execution time: 37 MS
console.log('Code execution time:' + (timestamp2 - timestamp1) + 'millisecond');

As can be seen from the above code and output result examples, JavaScript spliced the string variable str 90000 times, taking a total execution time of 37 milliseconds. The time will vary according to the operation speed of different computers.

5.4. 3_ [case] countdown

Countdown marks for discounted goods often appear on the activity pages of some e-commerce websites, showing that there are x days, X hours, X minutes and X seconds left before the end of the activity. Such countdown teaching results can be realized by using date objects.

The core algorithm of countdown is to subtract the current time from the input time, and the remaining time is the countdown time to be displayed. This needs to convert the time into a timestamp (milliseconds) for calculation, and convert the obtained milliseconds into days, hours, minutes and seconds.

The specific example code is as follows:

function countDown(time){
var nowTime = +new Date();
//+new Date() is new Date() Short for gettime () code, returns the current timestamp in milliseconds.
var inputTime = +new Date(time);
//Set the end timestamp of the activity.
var times  = (inputTime - nowTime) / 1000;
//To calculate the remaining milliseconds, it needs to be converted into seconds. The conversion rule is 1s / 1000ms.
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 + 'day' + h + 'Time' + m + 'branch' + s + 'second';
// Lines 5 to 13 calculate the number of days d, hours h, minutes m and seconds s, and use return to return.
}
// Example result: 23:06:10 on day 05
console.log(countDown('2019-10-22 10:56:57'));
// Output how much time is left before the specified end date 2019-10-22 10:56.57.

5.5_ Array object

Array objects in JavaScript can be created using new Array or literal "[]".

5.5. 1_ Array type detection

In development, it is sometimes necessary to detect whether the type of variable is array. For example, in two numbers. The required parameters must be an array one by one, and other types of values cannot be passed in, otherwise an error will occur. Therefore, at this time, you can check whether the parameter type is an array in the function. There are two common methods for array type detection: using instanceof operator and using array Isarray() method.

The example code is as follows:

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

In the above code, if the detection result is true, it means that the given variable is an array. If the detection result is false, it means that the given variable is not an array.

5.5. 2_ Add or remove array elements

JavaScript array objects provide methods to add or delete elements. You can add new array elements at the end or beginning of the array, or remove array elements at the end or beginning of the array.

Add or remove array elements:

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

It should be noted that the return values of the push() and unshift() methods are the length of the new array, while the pop() and shift() methods return the removed array elements.

Case: demonstration

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

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

5.5. 3_ [case] filter array

Case: it is required to eliminate the data with salary of 2000 or above in the array containing salary, and put the number less than 2000 back into the innovative array. The array is [1500120020021001800].

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);
// Equivalent to: newArr (newArr.length] = arr[i];
}
}

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

In the above code, the first line of code is the original array arr. The second line of code defines a new array newArr to store data with wages lower than 2000. The code in line 3 is judged by the if statement in the for loop statement. If it meets the requirements, use the push() method to store it in the new array newArr.

5.5. 4_ Array sorting

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

Sorting method:

Method nameFunction description
reverse()Invert the position of elements in the array. This method will change the original array and return a new array
sort()Sort the elements of the array. This method will change the original array and return a new array

Note that the return value of the reverse() and sort() methods is the length of the new array.

//Invert array
var arr = ['red', 'green', 'blue'];
arr.reverse();
console.log(arr);//Output result: (3) ["blue", "green","red"]
//The above demonstrates the use of the reverse() method to realize 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 the use of the sort() method to sort array elements from large to small.

return a - b;// In ascending order

5.5. 5_ Array index

In development, if you want to find the position of the specified element in the Array, you can use the retrieval method provided by the Array object.

Search method:

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

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 "= =", that is, only when it is congruent will it return a more successful result.

Case: demonstration,

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

In the above code, the lastIndexOf () method is used to retrieve the subscript of the last given value from the specified subscript position in the array. Different from the indexOf() retrieval method, the lastIndexOf() method defaults to reverse retrieval, that is, from the end of the array to the beginning of the array.

5.5. 6_ [case] array to remove duplicate elements

Next, we use a case to demonstrate the use of array index. It is required to remove duplicate elements in a set of data. 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

// Traverse the array. If an element in the array appears repeatedly, it will be 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 result: (4) ["blue","green"]

If it occurs, it will be added to the new array, otherwise it will not be added. In the fourth line of the code, if the element is judged, if the return value is - 1, it means that there is no element in the new array.

3 using the new array does not exist in the new array

5.5. 7_ Convert array to string

If you need to convert an array to a string, you can use the join() and toString() methods of the array object.

Convert array to string:

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

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

As can be seen from the above code, the join() and toString() methods can convert multidimensional arrays into strings, which are connected by commas by default. The difference is that the join() method can specify the symbol to connect array elements. In addition, when the array element is undefined, null or empty, the corresponding element will be converted to an empty string.

5.5. 8_ Other methods

JavaScript also provides many other array methods that are also commonly used. For example, fill array, connect array, intercept array elements, etc.

Other methods:

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

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

Case: the splice() method adds or deletes array elements at the specified position,

var arr = ['sky', 'wind', 'snow', 'sun'];
// Delete 2 meta indexes from the position with index 2
arr.splice(2, 2);
console.log (arr); 
// Output result: (2) ["sky", "wind"]

// Starting from the position with index 1, delete one element, and then add the snow element
arr.splice(1, 1, 'snow');
// Output result: (2) ["sky", "snow"]
console.log(arr);

// Add an array element starting at the position with index 1
arr.splice(1.0, 'hail', 'sun');
console.log(arr);
// Output results: (4) ["sky", "hail", "sun", "snow"]

In the above code, the first parameter of the splice() method is used to specify the subscript position to be added or deleted; The second parameter is used to delete the number of array elements from the specified subscript position. If it is set to 0, it means that the method only adds elements; The remaining parameters represent the array elements to be added, and if omitted, the elements will be deleted.

5.6_ String object

In JavaScript, string objects provide some properties and methods for string processing, which can easily realize string search, interception, replacement, case conversion and other operations.

5.6. 1_ Use of string objects

The String object is created using new String(). If a String is passed in the String constructor, the String will be saved in the returned String object.

Case: demonstration,

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

// Get string length, output result: 5
console.log(str.length);

Careful readers will find that in the previous study, you can use the method of "string variable. Length", which is very similar to accessing the length attribute of an object.

Case: demonstration,

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

In fact, strings are a basic wrapper type in JavaScript. Basic wrapper types in JavaScript include String, Number and Boolean, which are used to wrap basic data types into complex data types, so that basic data types also have properties and methods.

It should be noted that although the mechanism of Javascript basic wrapper type can enable ordinary variables to access properties and methods like objects, they are not object types.

Case: demonstration,

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

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

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

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

As can be seen from the above code, the obj returned using new String() is an object, but an ordinary string variable is not an object, it is just string type data.

5.6. 2_ Returns the position according to the character

String objects provide properties and methods for retrieving elements

The string object retrieves the properties and methods of the element:

membereffect
indexOf( search Value )Gets the position where search Value first appears in the string
lastIndexOf( search Value )Gets the last occurrence of search Value in the string

Case: demonstrate the use of indexOf() and lastIndexOf() methods,

var str = 'HelloWorld' ;

console.log( str.indexOf('o') );
// Get the position where "o" first appears in the string, and return the result: 4
console.log( str.lastIndexOf('o')  );
// Get the last position of "o" in the string and return the result: 6

It can be seen from the returned results that the position is calculated from 0. The position of the first character of the string is 0, the second character is 1, and so on. The position of the last character is the length of the string minus 1.

Case: find the location and number of occurrences of all specified elements in a set of strings. The string is' Hello World, Hello JavaScript '.

var str = 'Hello World,Hello Javascript';
var index = str.indexOf('o'); // First find the location where the first o appears.
var num = 0; // Set the number of o occurrences, with an initial value of 0.
while(index != -1){  // Judge the result of the return value of indexOf through the while statement
//If it is not - 1, continue to search later because indexOf can only find the first one,
//Therefore, the following search needs to be realized by using the second parameter, adding 1 to the current index,
//This allows you to continue searching.
console.log (index);// Output in sequence: 4, 7, 17
index = str.indexOf('o', index + 1);
num++;
}
console.log ('o The number of occurrences is:' + num);// o number of occurrences: 3

It should be noted that spaces in the string will also be treated as a character.

5.6. 3_ Returns characters based on position

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

String object is the method used to get a character

membereffect
charAt(index)Gets the character of the index position, which is calculated from 0
charCodeAt(index)Gets the ASCII code of the character at the index position
str [ index ]Gets the character at the specified position (new in HTML5)

Case: understand the use of charAt(), charCodeAt(), str [subscript],

var str = 'Apple';
console.log (str.charAt(3));// Output result: 1
console.log (str.charCodeAt(0));// Output result: 65 (ASCII code of character A is 65)
console.log(str[0]);// Output result: A

5.6. 4_ [case] count the most characters and times

Case: demonstrate the use of charAt() method. Through the program to count the most characters and times in the string

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

for (var i = 0; i < str.length; i++) {
var chars = str.charAt(i); 
// Use chars to 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 result: {A: 1, p: 2, 1:1,e:1}

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

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

// Output result: "the most frequent character is: p, which appears twice in total"
console.log('The characters that appear most are:' + ch + ',A total of' + max + 'second');

5.6. 5_ String operation method

String objects provide properties and methods for intercepting strings, connecting strings, and replacing strings

String objects are used to intercept, concatenate, and replace strings:

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

When the method in the above table is used to operate the string, the processing result is directly returned through the return value of the method, and the string itself will not be changed.

Case: demonstration,

var str = 'HelloWorld';
str.concat('!');     // Splice characters at the end of the string, result: HelloWorld!
str.slice(1, 3);     // Intercept the content from position 1 to position 3. Result: el
str.substring (5);  // Intercept the content from position 5 to the end. Result: World
str.substring(5, 7);  // Intercept the content from position 5 to position 7. Result: Wo
str.substr(5);      // Intercept the content from position 5 to the end of the string. Result: World
str.substring(5, 7);// Intercept the content from position 5 to position 7. Result: Wo
str.toLowerCase();  // Convert string to lowercase, result: helloworld
str.toUpperCase();  // Convert string to uppercase, result: HELLOWORLD
str.split('1');    // Use "1" to cut the string, and the result: [he "," owor "," d "]
str.split('1', 3);  // Limit cutting up to 3 times, result: ["he", "owor"]
str.replace('World','!');// Replace the string with the result: "Hello!"

5.6. 6_ [case] judge whether the user name is legal

Case: the length of the user name is required to be in the range of 3 ~ 10, and any case of the sensitive word admin is not allowed.

var name = prompt('Please enter user name');
if (name.length < 3 || name.length > 10){
alert('User name length must be within 3 ~ 10 between.');
} else if (name.toLowerCase().indexOf('admin') !== -1){
alert('The user name cannot contain sensitive words: admin. ');
}else{
alert('Congratulations, this user name is available');
}

The above code verifies the length of the user name by judging the length attribute; After converting the user name to lowercase, find out whether it contains the sensitive word admin. During implementation, the name is converted to lowercase and then searched. The user name can be checked no matter what case combination is used. The indexOf() method will return - 1 when the search fails, so judge the return value of the method to know whether the user name contains sensitive words.

5.7_ Value type and reference type

In JavaScript, basic data types (such as string, numeric, Boolean, undefined, null) are also called value types, and complex data types (objects) are also called reference types. The characteristic of reference type is that only the address of a reference is saved in the variable. When assigning a value to a variable, the object is not copied, but the reference of two variables to the same object.

Case: for example, obj1 and obj2 in the following code point to the same object.

//Create an object and save the reference of the object through the variable obj1
var obj1 = {name:'Xiao Ming', age:18};
// At this time, the object is not copied, but obj2 and obj1 variables refer to the same object

var obj2 = objl;
// Compare whether two variables refer to the same object
console.log (obj2 == obj1); // Output result: true
// Modify the properties of an object through obj2
obj2.name = 'Xiao Hong';
// Access the name attribute of the object through obj1
console.log (obj1.name) // Output result: Xiaohong

After the above code is executed, obj1 and obj2 variables reference the same object. At this time, whether obj1 or obj2 is used to operate the object, the actual operation is the same object.

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

Case: demonstrate the above overview:

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

In the above code, the object with name Xiaoming created in the first line of code is only referenced by obj1 at first. After executing the second line of code, both obj1 and obj2 reference the object. After executing the fourth line of code, only obj2 references the object. When an object is referenced by only one variable, if the variable is re assigned, the object will become the case without any variable reference. At this time, it will be automatically released by the JavaScript garbage collection mechanism.

When a variable of reference type is passed as a parameter of a function, its 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 results accessed outside the function by referencing the variables of the object are also modified.

Case: demonstrate the above overview,

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

In the above code, when the change() function is called, obj is modified in the change() function The value of name. After modification, outside the function, the result accessed by variables exceeding stu is the modified value, indicating that the variable stu and parameter obj refer to the same object.

Today's introductory study is temporarily over
Peace

🌊🌈 Previous review:

JavaScript learning:
Challenge JavaScript to get you started in the shortest time (I)
Challenge JavaScript to get you started in the shortest time (2)
Challenge JavaScript to get you started in the shortest time (3)
Challenge JavaScript to get you started in the shortest time (4)
HTML learning:
A ken's learning notes on HTML and CSS_ Basic HTML (Note 1)
A ken's learning notes on HTML and CSS_ HTML page elements and attributes (Note 2)
A ken's learning notes on HTML and CSS_ Text style properties (Note 3)
A ken's learning notes on HTML and CSS_ CSS3 selector (Note 4)
A ken's learning notes on HTML and CSS_ CSS box model (Note 5)
A ken's learning notes on HTML and CSS_ Floating and positioning (Note 6)
A ken's learning notes on HTML and CSS_ Application of forms (Note 7)
A ken's learning notes on HTML and CSS_ Multimedia technology (note 8)
A ken's learning notes on HTML and CSS_ CSS3 advanced application (note 9)

🌊🌈 About postscript:

Thank you for reading. I hope it can help you. If there are defects in the blog, please leave a message in the comment area or add contact information to the personal introduction of the home page. I thank every little partner for his comments
Original is not easy, "like" + "pay attention" + "collect" thank you for your support ❤

Topics: Javascript Front-end