preface
This chapter mainly introduces the knowledge of JavaScript objects;
1, Object
"Object" in JavaScript, an object is an unordered collection of related attributes and methods. All things are objects, such as strings, values, arrays, functions, etc.
Composition and use of objects
1. Objects are composed of attributes and methods
Attribute: the characteristic of a thing, which is represented by an attribute in an object (a common noun) Method: the behavior of things is often expressed in the object (common verb)
2. Use of objects
Attribute of object: the key in the "key value pair" in which specific data is stored in the object is called the attribute of the object, that is, the item in which specific data is stored in the object. Object method: the "key" in the "key value pair" of the stored function in the object is called the object method, that is, the item of the stored function in the object. Access the properties of the object: call the properties in the object:**object.Attribute name**;Another way to call properties in an object:**object['Attribute name']**,Note that the attributes in square brackets must be enclosed in quotation marks. Call the method of the object:**object.Method name()**;
Summary of variables, attributes, functions and methods:
①Variable: independent declaration and assignment, independent existence ②attribute:The variables in the object are called attributes and do not need to be declared. They are used to describe the characteristics of the object. ③Method: a method is a part of an object, a function is not a part of an object, and a function is a container that encapsulates operations separately. The functions in the object are called methods. Methods do not need to be declared and can be used"object.Method name()"Methods can be called to describe the behavior and function of the object. ④function:Alone, by"Function name()"Can be called.
console.log(star.name) // Call name property console.log(star['name']) // Call name property star.sayHi();
Three ways to create objects
1. Create objects with literal values
Create objects using object literals:
It's curly braces { } It contains the attributes and methods of expressing this specific thing (object);{ } It is expressed in the form of key value pairs -Key: equivalent to attribute name; -Value: equivalent to attribute value and can be any type of value (numeric type, string type, boolean type, function type, etc.)
// star is the object created var star = { name : 'pink', age : 18, sex : 'male', sayHi : function() { alert('Hello, everyone'); } };
2. Create an object using new Object
Create an Object through the built-in constructor Object. At this time, the andy variable has saved the created empty Object
var andy = new Object();
- Add properties and methods to an empty object
//Add attributes and methods to objects by manipulating them andy.name = 'pink'; andy.age = 18; // andy.age = 19 modify object properties andy.sex = 'Male;// andy.phoneNum = 110 add attribute andy.sayHi = function() { alert('hello everyone'); } obj.sayHi();Call the method of the object //The second is obj['sayHi '] (); // The first letter of Object() is capitalized; //new Object() requires the new keyword. The format used is: object Attribute = value
3. Create objects using constructors
Constructor is a special function, which is mainly used to initialize an object, that is, to assign initial values to object member variables. It is always used together with the new operator. We can extract some public properties and methods from the object and encapsulate them into this function.
Encapsulation format of constructor:
function Constructor name(Parameter 1, parameter 2, parameter 3...) { this.Property name 1 = Parameter 1; this.Property name 2 = Parameter 2; this.Property name 3 = Parameter 3; this.Method name = Function body; }
- Call format of constructor
var obj = new Constructor name(Argument 1, argument 2, argument 3); // In the above code, obj receives the object created by the constructor.
matters needing attention:
1. Constructor convention initial capitalization
2. this needs to be added in front of the properties and methods in the function to represent the properties and methods of the current object
3. retrun return result is not required in the constructor
4. When we create an object, we must call the constructor with new
Function of new keyword (interview question)
1.Create an empty object before the constructor code starts executing; 2.modify this Point, put this Point to the created empty object; 3.Execute the code in the constructor to add properties and methods to the new object 4.After the function is completed, return the created new object(So you don't need it in the constructor return)
// The factory function creates an object, which returns the created object to the function call function createPerson(name, age, job) { var person = new Object(); person.name = name; person.age = age; person.job = job; person.sayHi = function(){ console.log('Hello,everyBody'); } return person; } var p1 = createPerson('Zhang San', 22, 'actor');
2, Traversal object
for...in Statement is used to perform a circular operation on the attributes of an array or object. The syntax is as follows: for (variable in Object name) { // Execute code here } The variable in the syntax is user-defined. It needs to comply with the naming convention. Usually, we will write this variable as k perhaps key. for (var k in obj) { console.log(k); // k here is the attribute name console.log(obj[k]); // obj[k] here is the attribute value }
3, Built in object
Built in objects there are three types of objects in JavaScript: custom objects, built-in objects, and browser objects
The first two objects are the basic content of JS and belong to ECMAScript; The third browser object is unique to JS. JS API explains that built-in objects refer to some objects of JS language. These objects are used by developers and provide some common or most basic rather than necessary functions (properties and methods). The biggest advantage of built-in objects is to help us develop quickly.
Check documents
To learn how to use a built-in object, just learn how to use its common members. We can learn by looking up documents.
MDN:https://developer.mozilla.org/zh-CN/
var teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');
Brackets indicate whether to write or not
(1) , Math objects
It is not a constructor. It has the properties and methods of mathematical constants and functions, which is related to mathematics.
Property, method name | function |
---|---|
Math.PI | PI |
Math.floor() | Round down |
Math.ceil() | Round up |
Math.round() | The rounded version is rounded to the nearest. Note - 3.5. The result is - 3 |
Math.abs() | absolute value |
Math.max()/Math.min() | Find the maximum and minimum values |
Math.random() | Gets a random value in the range [0,1] |
Gets a random integer in the specified range
function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
(2) , Date object
Date object is different from Math object. Date is a constructor, so you need to instantiate it before you can use its specific methods and properties. The date instance is used to process date and time
Instantiate a Date object with Date
Get current time must be instantiated Gets the date object for the specified time
var now = new Date(); var future = new Date('2020/10/1') // Note: if no parameter is passed in when creating an instance, the date object obtained is the date object corresponding to the current time
Methods and properties using Date instances
- Month obtained by getMonth() method + 1 = current month
- Parameters are usually written in numeric or string type '2019-10-1 8:8:8'
//Parameters are usually written in numeric or string form '2019-10-1 8:8:8' var date1 = new Date(2019,10,1);
Format date: mm / DD / yy
var date = new Date(); console.log(date.getFullYear()); //Returns the year 2020 of the current date console.log(date.getMonth() + 1); //The month returned in the month is 1 month smaller. Remember to add 1 month to the month console.log(date.getDate()); //What number is returned console.log(date.getDay); //Monday returns 1, Saturday returns 6, and Sunday returns 0 //We write a Sunday, September 6, 2020 var year = date.getFullYear(); var month = date.getMonth() + 1; var dates = date.getDate(); var day = date.getDay(); if (day == 0) { day = "Sunday"; } console.log("Today is" + year + "year" + month + "month" + dates + "day" + day);
Format date hour minute second
var date = new Date(); console.log(date.getHours()); //Time console.log(date.getMinutes()); //branch console.log(date.getSeconds()); // second //Encapsulate a function to return the current time, minute and second format 08:08:08 function getTimer() { var time = new Date(); var h = time.getHours(); var h = h < 10 ? "0" + h : h; var m = time.getMinutes(); var m = m < 10 ? "0" + m : m; var s = time.getSeconds(); var s = s < 10 ? "0" + s : s; return h + ":" + h + ":" + s; } console.log(getTimer());
Gets the total number of milliseconds (timestamp) of the Date
Based on milliseconds since January 1, 1970 (world standard)
// Instantiate Date object var now = new Date(); // 1. Used to obtain the original value of the object console.log(now.valueOf()) console.log(now.getTime()) // 2. Simple writing can do this (the most commonly used) var now = + new Date(); // 3. The method provided in HTML5 has compatibility problems var now = Date.now();
Countdown case:
- The input time minus the current time is the remaining time, that is, the countdown.
2. Use the time stamp to subtract the total milliseconds of the current time from the total milliseconds of the user's input time,
The result is the number of milliseconds remaining
3. Convert the total milliseconds of the remaining time into days, hours, minutes and seconds (timestamp conversion hours, minutes and seconds)
The conversion formula is as follows:
D = parseInt (total seconds / 60 / 60 / 24) / / calculate days
H = parseInt (total seconds / 60 / 60% 24) / / calculate hours
M = parseInt (total seconds / 60% 60)// Calculate minutes
S = parseInt (total seconds% 60)// Calculate current seconds
// Implementation of countdown case encapsulation function function countDown(time) { var nowTime = +new Date(); // Returns the total number of milliseconds of the current time var inputTime = +new Date(time); // Returns the total number of milliseconds of user input time var times = (inputTime - nowTime) / 1000; // times is the total number of seconds remaining var d = parseInt(times / 60 / 60 / 24); // day d = d < 10 ? "0" + d : d; var h = parseInt((times / 60 / 60) % 24); //Time h = h < 10 ? "0" + h : h; var m = parseInt((times / 60) % 60); // branch m = m < 10 ? "0" + m : m; var s = parseInt(times % 60); // Current seconds s = s < 10 ? "0" + s : s; return d + "day" + h + "Time" + m + "branch" + s + "second"; } console.log(countDown("2020-10-1 18:00:00")); var date = new Date(); console.log(date);
(3) , array objects
Two ways to create arrays
1. Literal mode var arr = [1,"test",true]; 2. Instantiate array objects new Array()var arr = new Array(); Note: in the above code arr Create an empty array, if you need to use the constructor Array To create a non empty array, you can pass in parameters when creating the array If only one parameter is passed in(number),The parameter specifies the length of the array. If more than one parameter is passed in, the parameter is called an element of the array.
Detect whether it is an array
1. instanceof operator
instanceof You can determine whether an object is an instance of a constructor
var arr = [1, 23]; var obj = {}; console.log(arr instanceof Array); // true console.log(obj instanceof Array); // false
2. Array.isArray()
Array.isArray()Used to determine whether an object is an array, isArray() yes HTML5 Methods provided in
var arr = [1, 23]; var obj = {}; console.log(Array.isArray(arr)); // true console.log(Array.isArray(obj)); // false
Pay attention to the usage of typeof
typeof is used to determine the type of variable
var arr = [1, 23]; console.log(typeof arr) // The object object arr is an instance of the constructor and is therefore an object data type
Methods for adding and deleting array elements
There are methods to add and delete elements in the array. Some methods are shown in the table below
var arr = [1, 2, 3]; console.log(arr.push(4, 5)); // 5 add elements to the end of the array arr.pop(); //Deletes the last value of the array and returns console.log(arr); // [1,2,3,4] // Adds an element to the beginning of an array and returns the length of the array console.log(arr.unshift(5, 6)); // 6 array becomes [5,6,1,2,3,4] console.log(arr.shift()); // 5 delete the element at the beginning of the array and return the value
Array sort()
There are methods to sort the array itself in the array. Some methods are shown in the table below
Method name | explain | Modify original array |
---|---|---|
reverse() | Invert the order of elements in the array without parameters | 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: the sort method needs to pass in parameters (functions) to set ascending and descending sorting
If incoming“ function(a,b){ return a-b;}",In ascending order If incoming“ function(a,b){ return b-a;}",In descending order
// Pit array sort (bubble sort) return a - b will be in ascending order // The writing method is fixed as follows: var arr1 = [13,4,77,1,7]; arr1.sort(function(a,b){ return a-b; }); console.log(arr1);
Array flip reverse()
// 1. Flip array var arr = ['pink', 'red', 'blue']; arr.reverse(); console.log(arr);
Custom write method of reverse function
function reverse(arr){ var newArr = []; for (var i = arr.length - 1; i >= 0; i--){ newArr[newArr.length] = arr[i]; } return newArr; }
Array index method
There are methods to obtain the index value of the specified element of the array. Some methods are shown in the table below
var arr = [1, 2, 3, 4, 5, 4, 1, 2]; // Find index of element 2 console.log(arr.indexOf(2)); // 1 // Find the last index of element 1 in the array console.log(arr.lastIndexOf(1)); // 6
Array de duplication case:
// Array de duplication ['c ',' a ',' Z ',' a ',' x ',' a ',' x ',' C ',' B '] requires the removal of duplicate elements in the array. // 1. Objective: select the non duplicate elements in the old array and put them into the new array. Only one duplicate element is retained and put them into the new array for duplication. // 2. Core algorithm: we traverse the old array, and then take the old array element to query the new array. If the element has not appeared in the new array, we will add it, otherwise we will not add it. // 3. How do we know that the element does not exist? Use the new array Indexof (array element) if - 1 is returned, it means that there are no changed elements in the new array // Encapsulating a de duplication function unique function unique(arr) { var newArr = []; for (var i = 0; i < arr.length; i++) { if (newArr.indexOf(arr[i]) === -1) { newArr.push(arr[i]); } } return newArr; } // var demo = unique(['c', 'a', 'z', 'a', 'x', 'a', 'x', 'c', 'b']) var demo = unique(['blue', 'green', 'blue']) console.log(demo);
Convert array to string
There are methods to convert an array into a string in the array. Some methods are shown in the table below
Note: if the join method does not pass in parameters, the elements will be spliced according to ","
var arr = [1, 2, 3, 4]; var arr2 = arr; var str = arr.toString(); // Convert array to string console.log(str); // 1,2,3,4 var str2 = arr2.join("|");//Converts an array to a string according to the characters you type console.log(str2);
Other methods
var arr = [1, 2, 3, 4]; var arr2 = [5, 6, 7, 8]; var arr3 = arr.concat(arr2); console.log(arr3); // [1,2,3,4,5,6,7,8] // slice(begin,end) is a left closed right open interval [1,3] // Intercept from index 1 to index 3 var arr4 = arr.slice(1, 3); console.log(arr4); // [2,3] var arr5 = arr2.splice(0, 3); console.log(arr5); // [5,6,7] console.log(arr2); // [8] Splice() affects the original array
(4) , string object
Basic wrapper type: to facilitate the operation of basic data types, JavaScript also provides three special reference types: String, Number and Boolean.
The basic wrapper type is to wrap a simple data type into a complex data type, so that the basic data type has properties and methods.
//What's wrong with the following code?
var str = 'andy';
console.log(str.length); // 4
In principle, basic data types have no attributes and methods, while objects have attributes and methods, but the above code can be executed because js will package basic data types as complex data types. The execution process is as follows:
// 1. Generate temporary variables and wrap simple types into complex data types var temp = new String('andy'); // 2. Assign a value to the character variable we declare str = temp; // 3. Destroy temporary variables temp = null;
Immutability of string
-
The immutability of the string means that the value inside is immutable. Although it seems that the content can be changed, the address has changed and a new memory space has been opened up in the memory.
-
When re assigning a value to a string variable, the previously saved string of the variable will not be modified. Re assigning a value to the string in memory will re open up space in memory. This feature is the immutability of the string.
-
Due to the immutability of strings, there will be efficiency problems when "splicing a large number of strings"
-
All methods of string will not modify the string itself (the string is immutable), and a new string will be returned after the operation is completed
Returns the position according to the character
String through the basic wrapper type, you can call some methods to operate the string. The following is the method to return the position of the specified character:
var str = "anndy"; console.log(str.indexOf("d")); // 3 //Specifies that the character "d" is found starting at an index number of 4 console.log(str.indexOf("d", 4)); // -1 console.log(str.lastIndexOf("n")); // 2
Case: find the location and number of occurrences of all o in the string "abcoefoxyozopp"
- First find the location where the first o appears
- Then, as long as the result returned by indexOf is not - 1, continue to look back
- Because indexOf can only find the first one, the subsequent search uses the second parameter to add 1 to the current index to continue the search
var str = "oabcoefoxyozzopp"; var index = str.indexOf("o"); var num = 0; while (index !== -1) { console.log(index); num++; index = str.indexOf("o", index + 1); }
Returns characters based on position
String through the basic wrapper type, you can call some methods to operate the string. The following is the character at the specified position returned according to the position:
// Returns characters based on position // 1. charAt(index) returns characters according to position var str = 'andy'; console.log(str.charAt(3)); // y // Traverse all characters for (var i = 0; i < str.length; i++) { console.log(str.charAt(i)); } // a n d y // 2. charCodeAt(index) //Returns the character ASCII value of the corresponding index number. Purpose: to determine which key the user pressed console.log(str.charCodeAt(0)); // 97 // 3. str[index] H5 NEW console.log(str[0]); // a
Case: judge a string 'abcoefoxyozzopp' The character that appears the most times in and counts its times Core algorithm: Using charAt() Traverse this string Store each character to the object. If the object does not have this attribute, it will be 1. If it exists, it will be 1 +1 Traverse the object to get the maximum value and the character. Note: in the process of traversal, each character in the string is stored in the object as the attribute of the object, and the corresponding attribute value is the number of occurrences of the character
var str = "abcoefoxyozzopp"; var o = {}; for (var i = 0; i < str.length; i++) { var chars = str.charAt(i); // chars is each character of the string if (o[chars]) { // o[chars] gets the attribute value o[chars]++; } else { o[chars] = 1; } } console.log(o); // 2. Traversing objects var max = 0; var ch = ""; for (var k in o) { // k is the attribute name // o[k] gets the attribute value if (o[k] > max) { max = o[k]; ch = k; } } console.log(max); console.log("The maximum number of characters is" + ch);
String operation methods: splicing, substring, replacement and segmentation
String through the basic wrapper type, you can call some methods to operate the string. The following are some operation methods:
// String operation method // 1. concat('string 1 ',' string 2 '...) var str = 'andy'; console.log(str.concat('red')); // andyred // 2. substr('intercept start position ',' intercept several characters'); var str1 = 'The spring breeze of reform is blowing all over the ground'; // The first 2 is the 2 of the index number, starting from the second 2, and the second 2 is the number of characters console.log(str1.substr(2, 2)); // spring breeze
replace() method
The replace() method is used to replace some characters with others in the string. Its format is as follows:
character string. Replace (string to be replaced, string to be replaced with);
split() method
The split() method is used to split strings, which can be split into arrays. After segmentation, a new array is returned.
Its format is as follows:
character string. split("split character")
// 1. The replacement character replace('replaced character ',' replaced character ') will only replace the first character var str = "andyandy"; console.log(str.replace("a", "b")); // bndyandy // There is a string 'abcoefoxyozzopp' that requires all o's in it to be replaced with* var str1 = "abcoefoxyozzopp"; while (str1.indexOf("o") !== -1) { str1 = str1.replace("o", "*"); } console.log(str1); // abc*ef*xy*zz*pp // 2. Convert characters to array split('separator ') // We learned earlier that join converts an array into a string var str2 = "red, pink, blue"; console.log(str2.split(",")); //[red,pink,blue] var str3 = "red&pink&blue"; console.log(str3.split("&")); // [red,pink,blue]
4, Simple and complex data types
Simple type (basic data type, value type) ": during storage, the value itself is stored in the variable, including string, number, boolean, undefined and null
"Complex data type (reference type)": during storage, only the address (Reference) is stored in the variable. Objects (system objects, user-defined objects) created through the new keyword, such as Object, Array, Date, etc;
Stack
Stack space allocation difference:
-
Stack (operating system): the operating system automatically allocates and releases the parameter values of stored functions and the values of local variables. Its operation mode is similar to the stack in the data structure; Simple data types are stored on the stack
-
Heap (operating system): it stores complex types (objects), which are generally allocated and released by the programmer. If the programmer does not release them, they are collected by the garbage collection mechanism.
//The simple data type null returns an empty object object
var timer = null;
console.log(typeof timer);
//If we plan to store a variable as an object in the future and don't think about what to put for the time being, it will be null at this time
// 1. Simple data types are stored in the stack, which directly opens up a space to store values
// 2. Complex data types first store the address hexadecimal representation in the stack, and then this address points to the data in the heap
Storage of simple data types
The data of value type variables is stored directly in variables (stack space)
Storage of complex data types
Reference type variables (stack space) store addresses, and real object instances are stored in heap space
Simple type parameters
The formal parameter of a function can also be regarded as a variable. When we pass a value type variable as a parameter to the formal parameter of a function, we actually copy the value of the variable in the stack space to the formal parameter. Then any modification to the formal parameter inside the method will not affect the external variable.
function fn(a) { a++; console.log(a); } var x = 10; fn(x); console.log(x);
The operation results are as follows:
Complex data type parameters
The formal parameter of a function can also be regarded as a variable. When we pass a reference type variable to the formal parameter, we actually copy the heap address saved by the variable in the stack space to the formal parameter. The formal parameter and the actual parameter actually save the same heap address, so we operate on the same object.
function Person(name) { this.name = name; } function f1(x) { // x = p console.log(x.name); // 2. What is this output? x.name = "Xue You Zhang"; console.log(x.name); // 3. What is this output? } var p = new Person("Lau Andy"); console.log(p.name); // 1. What is this output? f1(p); console.log(p.name); // 4. What is this output?
The operation results are as follows: