Basic JavaScript syntax (2)
8, Function
1. Concept of function
In JS, many codes with the same or similar functions may be defined. These codes may need to be reused. Although the for loop statement can also realize some simple repetitive operations, it has limitations. At this time, we can use the functions in JS
Function: encapsulates a code block that can be repeatedly called and executed. Through this code block, a large amount of code can be reused
2. Use of functions
Declarative function
function Function name() { // Function set } function sayHi() { console.log("hi~~") }
Function declares the keyword of the function, all lowercase
A function is to do something. The name of a function is usually a verb
Functions do not call and do not execute themselves
Call function
Function name() // Call function sayHi()
When calling a function, be sure not to forget to add parentheses
Declaring the function itself will not execute the code, and the code in the function body will be executed only when the function is called
3. Encapsulation of functions
Function encapsulation is to encapsulate one or more functions through functions, and only provide a simple function interface
function getSum() { var sum = 0; for (var i = 1; i <= 100; i++){ sum += i; } console.log("And are:" + sum); } getSum();
4. Parameters of function
Formal parameters: formal parameters, parameters passed during function definition
Arguments: actual parameters, parameters passed during function call, and arguments are passed to formal parameters
The function is implemented to repeat different codes
function Function name(Formal parameter 1, Formal parameter 2···) { // Inside the parentheses of the declared function are formal parameters } Function name(Argument 1, Argument 2···) // Inside the parentheses of the function call are the arguments
Execution process of formal parameters and arguments
-
A formal parameter is a variable that receives an argument
function eat(arg) { console.log(arg); } eat("potato"); eat("meat");
-
Function parameters can be or not
-
Attention
- Multiple parameters are separated by commas
- Formal parameters can be regarded as undeclared variables
Parameter matching of function
If the number of arguments is consistent with the number of arguments, the result will be output normally
If the number of arguments is more than the number of formal parameters, the number of formal parameters will be obtained
If the number of arguments is less than the number of formal parameters, the formal parameters that do not receive values are undefined
proposal
- Try to match the number of arguments with the number of formal parameters
5. Function return value
return statement
- Sometimes, we want the function to return the value to the caller, which can be achieved by using the return statement
function Function name() { return Return value; } Receive variable = Function name();
-
Our function only implements a certain function, and the final result needs to be returned to the caller of the function. This can be achieved through return
-
As long as the function encounters return, it will return the following results to the caller of the function
function getReturn() { return 10; } var num = getReturn(); // Receive return value console.log(num)
matters needing attention
-
return stop function
-
Return can only return one value. If multiple values are separated by commas, the returned result is the last value
function getResult(num1, num2) { return [num1+num2, num1-num2, num1*num2, num1/num2] } // Use an array to hold multiple return values
-
If the function does not return, it returns undefined
function fuc1() { var a = 1; } function fuc2() { return 2; } console.log(fuc1()); // No return returns undefined console.log(fuc2());
-
return can also be used to terminate a loop
6, arguments
When we are not sure how many parameters are passed, we can use arguments to get them. In JS, argument is actually a built-in object belonging to the current function. All functions have a built-in arguments object, which stores all the arguments passed
function fun() { console.log(arguments); // It stores all the passed argument objects console.log(arguments.length); // Has the length attribute of an array } fun(1, 21, 32);
- arguments: pseudo array, not a real array
- Has the length attribute of an array
- Stored by index
- It doesn't have some methods of real arrays, such as pop() push()
- Only functions have arguments objects, and each function has built-in arguments
// Find the maximum value of any number function getMax() { var max = 0; for (var i = 1; i < arguments.length; i++) { if (max < arguments[i]) { max = arguments[i]; } } console.log(max); } getMax(1, 2, 3, 8, 0, 6, 89)
7. Function call function
Because each function is an independent code block used to complete special tasks, it is often used to call each other
function fn1() { console.log(11); fn2(); // The fn2 function was called at fn1 } function fn2() { console.log(34); fn1(); } fn1();
8. Declaration of functions
-
Using keywords to customize functions
function fu1() {}
-
Using function expressions (anonymous functions)
var Variable name = function() {} // The calling method is the same
The declaration method of function expression is similar to that of variable declaration, except that the value is stored in the variable and the function is stored in the expression
9, Scope
1. Overview
Generally speaking, the name used in a piece of program code is not always valid and available, and the scope of code that limits the availability of this name is the scope of this name. The use of scope improves the locality of program logic, enhances the reliability of program and reduces name conflict
2. Global scope
The entire Script tag, or a separate JS file, can be used anywhere
be careful
- If there is no declaration inside the function, the directly assigned variable is also a global variable
- Global variables are destroyed only when the browser is closed, which takes up more memory
3. Local scope
Inside the function is the local scope. The name of this code is only inside the function, and its effect and function
be careful
- The formal parameters of a function can also be regarded as local variables
- Local variables will be destroyed after the execution of our program, which saves resources
At this stage, JS does not have a block level scope. A new block level scope was added in es6
4. Scope chain
As long as it is code, it has at least scope
The local scope written in the function. If there is a local scope in the function, another scope can be born in this scope
According to the mechanism that internal functions can access external function variables, using chain search to determine which data can be accessed by internal functions is called scope chain (proximity principle)
5. Pre analysis
JS code is executed by the JS interpreter in the browser. JS parser can run JS code in two steps: pre parsing and code execution
- Pre parsing: the JS engine will promote all var and function s in JS to the front of the current scope
- Variable pre parsing (variable promotion)
- Variable promotion is to promote all variable declarations to the front of the current scope without promoting the assignment operation
- Function promotion
- That is to promote all function declarations to the front of the current scope without calling functions
- Variable pre parsing (variable promotion)
- Code execution: execute from top to bottom in the order of code writing
10, Custom object
1. Concept
In JS, an object is an unordered collection of related attributes and methods. Everything is an object, such as string, value, array, function, etc
Objects are composed of properties and methods
- Attributes: characteristics of things. To represent (a noun) with attributes in an object
- Method: the behavior of things, expressed by method in the object (verb)
When saving a value, you can use variables, and when saving multiple values (a set of values), you can use arrays. What if you want the full value?
The object expression structure in JS is clearer and more powerful
2. Create object
Differences between variable attribute function and method
- Same point
- They all store data
- Variables are declared and assigned separately. When used, the variable name is written directly and exists separately
- Property, which does not need to be declared in the object, must be an object when used attribute
- Similarities between functions and methods
- It's all about realizing certain functions and doing certain things
- Differences between functions and methods
- The function is declared separately, and the function name () exists separately when called
- Method, in the object, the object name when calling Method name ()
There are three main ways to create objects in JS
-
Creating objects with literal values
-
Literal amount of object: curly braces {} contain the attributes and methods to express this specific thing (object)
var obj = { name: "zhansan", age: 2, sex: "male", sayHi: function() { console.log("hi~~"); } }; // An empty object was created // When we call the object, we take the object name Attribute name console.log(obj.name); // The second method is object name ["attribute name"] consloe.log(obj["name"]); // The method object name of the calling object Method name () obj.sayHi()
- The attributes or methods inside are in the form of key value pairs
- Multiple attributes or methods are separated by commas
- The method colon is followed by an anonymous function
-
-
Creating objects with new objects
var obj = new Object(); // An empty object was created obj.nam = "zhannsan"; obj.age = 18; obj.sex = "female"; obj.sayHi = function() { console.log("hi~~"); }
- We use the equal sign assignment method to add the attributes and methods of the object
- Each property and method ends with a semicolon
- The method of calling the property is the same
-
Creating objects with constructors
The first two methods of creating objects can only create one object at a time
We create one object at a time. Many of the properties and methods are the same. We can only copy them
Therefore, we can use the method of function to repeat these same codes. We call this function constructor; Because this constructor is different, it encapsulates not ordinary code, but objects - the abstraction of constructor is to abstract some of the same properties and methods in our objects and encapsulate them into functions
// We need to create the same attributes of the objects of the four heavenly kings: name, age and gender. The same method: singing /* function Constructor name (){ this.Attribute = value; this.Method = function() {} } new Constructor name ()// Call function */ function Star(uname, age, sex) { this.name = uname; this.age = age; this.sex = sex; this.sing = function(song) { console.log(song); } } var ldh = new Star("Lau Andy", 18, "male", "Ice rain"); console.log(ldh); // The object returned by the call is an object
Constructor names should be capitalized
Our constructor doesn't need to write return to return the result
If we want a constructor, we must use new
We just need to call the function new Star() to create an object
Our properties and methods must be preceded by this
- Relationship between constructor and object
- Constructor refers to a large class, which is similar to the class in Java language
- An object refers especially to a specific thing
- The process of creating an object by our constructor is also called object instantiation
- new keyword execution procedure
- The new constructor creates an empty object in memory
- this will point to the empty object just created
- Execute the code in the function and add properties and methods to the empty object
- Return this object
- Relationship between constructor and object
3. Traversal object
for ... The in statement is used to perform a circular operation on the attributes of an array or object
var obj = { name: "zhansan", age: 2, sex: "male", sayHi: function() { console.log("hi~~"); } }; // Syntax: for (variable in object) {} for (var k in obj) { console.log(k); // The result is the property name console.log(obj[k]); // Get variable }
11, Built in object
1. Concept
There are three kinds of objects in JS: custom object, built-in object and browser object
Built in objects refer to the built-in objects of JS language, which are used by developers and provide some commonly used or most basic and necessary functions (properties and methods)
JS provides several built-in objects: Math, Date, Array, String, etc
2. 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 / W3C To query
3. Math object
It is not a constructor, so we don't need to use the new method, just use it directly
console.log(Math.PI); // PI console.log(Math.max(1, 99, 3)); // Find the maximum value. If there is no parameter, return - infinity console.log(Math.min(1, 99, 3)); // Find the minimum value console.log(Math.abs(-1)); // Absolute value, implicit conversion exists console.log(Math.floor()); // Round down Math.ceil() // Round up Math.round() // Round to the nearest, note - 3.5 = - 3, 3.5 = 4
Encapsulate your own mathematical objects
var myMath = { PI: 3.14155926, max: function() { var max = arguments[0]; for (var i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max; }, min: function() { var min = arguments[0]; for (var i = 0; i < arguments.length; i++) { if (arguments[i] < min) { min = arguments[i]; } } return min; } } console.log(myMath.PI); console.log(myMath.max(1, 5, 9)); console.log(myMath.min(1, 5, 9));
Random number method
Math.random() returns a random decimal (0 < = x < 1)
console.log(Math.random()); // No parameters are required
We want to get a random integer between two numbers and include these two integers
Math.floor(Math.random() * (max - min + 1)) + min;
function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(getRandom(1, 10));
Figure guessing game
function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // Generate random numbers from 1 to 10 var rand_num = getRandom(1, 10); while (true) { var num = parseInt(prompt("Please enter the number to guess (1) <= x <= 10)")); if (num === rand_num) { alert("So handsome, you guessed right!"); break; } else if (num > rand_num) { alert("Sorry, big guess! come on."); } else { alert("Sorry, it's too small! dear"); } }
4. Date object
It is a constructor and must be called with new to create our date object
var date = new Date(); console.log(date); // If there are no parameters, return the current time // Common writing methods of parameters: numeric type and string type var date1 = new Date(2022, 1, 25); console.log(date1); // Return 2022.2, numeric type var date2 = new Date("2022-1-25 8:8:8"); console.log(date2); // Return 2022-1, string type
Date object is different from Math object. It is a constructor, so we need to instantiate it before using it
The Date instance is used to process Date and time
Date formatting
var date = new Date(); console.log(date.getFullYear()); //Returns the year of the current date console.log(date.getMonth() + 1); // Get the current month, one month smaller console.log(date.getDate()); // Return date console.log(date.getDay()); // 0 is returned on Sunday, and others are normal var year = date.getFullYear(); var month = date.getMonth() + 1; var date = date.getDate(); var day = date.getDay(); var hour = date.getHours(); var mit = date.getMinutes(); var sec = date.getSeconds(); console.log("Today is:" + year + "year" + month + "month" + date + "day" + "week" + day)
// It is required to encapsulate a function to return the current time 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()); //Format output
Gets the total number of milliseconds for the period
Starting from January 1, 1970, get the number of milliseconds, also known as timestamp
// Get through valueOf(), or getTime() var date = new Date(); console.log(date.valueOf()); // Milliseconds from January 1, 1970 console.log(date.getTime()); // Simple writing var date1 = +new Date(); console.log(date1); // Method in H5 console.log(Date.now());
Countdown case
Core algorithm: the input time minus the current time is the remaining time, that is, the countdown, but you can't subtract the hours, minutes and seconds
Using the timestamp, the total number of milliseconds of the user input time minus the total number of milliseconds of the current time is the number of milliseconds of the remaining time
Convert the number of milliseconds of the remaining time into days, hours, minutes and seconds (time stamp into minutes and seconds)
function countDown(time) { var nowTime = +new Date(); // Get current timestamp var inputTime = +new Date(time); // Returns the total timestamp of the time entered by the user var times = (inputTime - nowTime) / 1000; // time is the total number of milliseconds remaining var d = parseInt(times / 60 / 60 / 24 ); 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"; } console.log(countDown("2022-2-1 24:00:00"));
5. Array object
Create array
-
Using array literals
var arr = [1, 2, 3];
-
Using Array objects
var arr1 = new Array(2); // Created an empty array with a length of 2 console.log(arr1); var arr2 = new Array(2, 3); // Equivalent to var arr2 = [2, 3] console.log(arr2);
Detect whether it is an array
-
instanceof operator, which can be used to detect whether it is an array
var arr = []; var obj = {}; console.log(arr instanceof Array); // true console.log(obj instanceof Array); // false
-
Array. Isarray (parameter);
console.log(Array.isArray(arr)); // true
Add and remove
Method name | explain | Return value |
---|---|---|
Push (parameter) | Add one or more elements at the end and pay attention to modifying the original array | Returns the new length |
pop() | Delete the last element of the array, reduce the length of the array by one, and there are no parameters | Returns the value of the element it deleted |
Unshift (parameter 1 ···) | Add one or more elements to the beginning of the array, and pay attention to modifying the original array | Returns the new length of the array |
shift() | Delete the first element of the array, reduce the length of the array by one, and have no parameters | Returns the value of the first element |
var arr = []; console.log(arr.push(4, "pink")); console.log(arr); // If there is a return value, the original array will also change console.log(arr.unshift("red", 2, 10)); console.log(arr); // If there is a return value, the original array will also change console.log(arr.pop()); // Returns the deleted element console.log(arr.shift()); // Returns the deleted element
sort
Method name | explain | Modify original array |
---|---|---|
reverse() | Invert elements in an array | This method will change the original array and return a new array |
sort() | Sort array elements | This method will change the original array and return a new array |
var arr = [1, 2, 3]; arr.reverse(); console.log(arr); arr.sort(function(a, b) { return a - b; // Ascending arrangement // return b - a; // Descending order }); console.log(arr);
Indexes
Method name | explain | Return value |
---|---|---|
indexOf("character to find", [starting position]) | Finds the first index of a given element in an array | Returns the index number, if any; Conversely, - 1 is returned |
lastIndexOf() | The index of the last in the array | Returns the index number, if any; Conversely, - 1 is returned |
Array de duplication
- Objective: select the non repeating elements in the old function and put them into the new array. Only one repeating element is kept and put them into the new array
- Core algorithm: 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
var oldArr = ["c", "a", 'z', 'a', 'x', 'c', 'b']; function unique(arr) { var newArr = []; for (var i = 0; i < oldArr.length; i++) { if (newArr.indexOf(oldArr[i]) === -1) { // No element returned - 1 newArr[newArr.length] = oldArr[i]; } } return newArr; } console.log(unique(oldArr));
Convert array to string
method | explain | Return value |
---|---|---|
toString() | Convert the array into a string, separating each item with a comma | Returns a string |
join("separator") | Method is used to convert all elements in the array into a string | Returns a string |
var arr = [1, 2, 3]; console.log(arr.toString()); console.log(arr.join("&"));
6. String object
Basic package type
Is to wrap simple data types into complex data types
var str = "andy"; var temp = new String("any"); str = temp; temp = null; // Destroy temp variable
String immutable
It means that the value inside is immutable. Although it seems that the content can be changed, in fact, the memory address has changed and a new memory space has been opened up in the memory
Indexes
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
var str = "hello"; console.log(str.indexOf("h", 1)); // Find from the position where the index number is 1 // Find where characters appear var str = "abcoefoxyozzopp"; var index = str.indexOf("o"); var num = 0; while (index !== -1) { console.log(index); num ++; index = str.indexOf("o", index + 1); } console.log("The number of occurrences is:" + num);
Returns characters based on position
-
charAt(index) returns characters based on position
var str = "hello"; console.log(str.charAt(3));
-
charCodeAt(index) obtains the ASCII code value at the specified position and determines which key the user presses
console.log(charCodeAt(0));
-
str[index] get the character that refers to the location
console.log(str(3));
case
Judge the character that appears the most times in a string and count its times
- Use charAt() to traverse the string
- Store each character to the object. If the object does not have this attribute, it will be 1, and if it exists, it will be + 1
- Traverse the object to get the maximum value and the character
var str = "abcoefoxyozzopp"; var obj = {}; 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]++; // o[chars] gets the attribute value } else { o[chars] = 1; } } console.log(o); // Traversal object var max = 0; var char1 = ""; for (var k in o) { // k gets the attribute name // o[k] gets the attribute value if (o[k] > max) { max = o[k]; char1 = k; } } console.log("The maximum characters are:" + char1 + ",yes:" + max + "individual");
Operation method
Method name | explain |
---|---|
concat(str1...) | The concat() method is used to connect two or more strings. Splice string, equivalent to +, + is more commonly used |
substr(start , length) | Starting from the start position (index number), the number taken by length |
slice(start, end) | Starting from start, intercept to the end position, and end cannot |
substring(startm, end) | Starting from the start position, intercept to the end position. End cannot go. It is basically the same as slice, but it will not accept negative values |
var str = "rub"; console.log(str.concat("red")); console.log(str.substr(0, 1));
Replace character
replace("replaced character", "replaced character")
var str = "andy"; console.log(str.replace("a", "b")); // If there are more than one, replace only the first character
Convert string to array
split("separator")
var str2 = "red, pink , blue"; console.log(str2.split(","));
7. Summary
Simple and complex data types
Simple data types are also called basic data types or value types, and complex types are also called reference types
-
Value type: simple data type / basic data type. What is stored in a variable refers to itself, so it is called value type
- Simple data type null, which is an empty object
- 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
-
Reference type: complex data type. Only the address (Reference) is stored in the storage variable, so it is called reference data type
Objects created through the new keyword (system objects, custom objects)
Heap and stack
Stack space allocation difference:
-
Stack (operating system): the operating system automatically allocates and releases the parameter values of the stored function and the values of local variables. Its operation mode is similar to the stack in the data structure
Simple data types are stored in the stack
-
Heap (operating system): it stores complex types (objects), which are generally allocated and released by programmers. If programmers do not release, there is a garbage collection mechanism to collect them
Complex data types are stored in the heap
memory allocation
- Simple data types are stored in the stack, which directly opens up a space to store values
- When complex data types are stored in the heap, first store the address in the stack, which points to the data in the heap
Chuan Shen
Simple data type
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
Complex data type
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 of 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