JavaScript Summary day1
This set of summary notes is mainly for students who have studied other advanced languages, because I omitted some of the same grammatical functions as the advanced ones! If you go into detail, the main functions of JS will be relied on before they are involved. This series of articles mainly summarizes the functions of js.
Composition of JS
ECMAScript: JavaScript syntax
DOM: Page Document Object Model
BOM: Browser Object Model
JS Writing Position
Embedded: Just like the embedded style, script tags are written inside the header tag (in fact, script tags can be written next to html files, usually within the header tag).
Inline: Write directly inside an HTML element.
External introduction: js files are introduced externally, and file locations are introduced in the src attribute in script tags.
Example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- embedded js write --> <script> //alert('inline 1'); </script> <!-- External introduction js file --> <script src="js File Address"></script> </head> <body> <!-- Inline js Write directly to the inside of an element --> <input type="button" value="Click" onclick="alert('Inline')"/> </body> </html>
Notes
//: Shortcut for single-line comments: ctrl + /
/* */: Shortcut keys for multi-line comments: Default: shift + alt + / Recommended change to: shift + ctrl + /
Input and Output Statements
Alert ("warning statement"); browser pop-up alert box
console.log("print information"); browser console prints output information
prompt("prompt message");:The browser pops up a prompt box with an input box to assign values to variables.
data type
js is a dynamic language The data type of a variable can be changed
Simple data type
Number: Number, containing integer and floating point defaults: 0
Boolean: Boolean type, such as true, false, equivalent to 1, 0 defaults: false
String: String type. Default value: ""
Undefined:var a;The variable a is declared but not assigned, in which case a = undefined default: undefined
Null: Null value.
Infinity: Infinity
-Infinity: Infinity
NaN: Non-numeric value
isNaN(): Returns false if it is a number or true if it is not
String.length(): Finds the length of the string.
Strings are stitched together into strings when added to any type
+sign summary trick: add values, connect characters
typeof: Detect what type this is
Example:
alert(typeof 13);
Other types of character conversion
Method:
.toString()
String()
Add to String
Example:
//Method 1: alert(num.toString()); //Method 2: alert(String(num)); //Method 3: alert(""+num);
Replace other types with numbers
Method:
parselnt(): Converts a string to an integer numeric type
parseFloat(): Converts a String type to a floating point numeric type
Number(): Converts a String type to a numeric type
Arithmetic implicit conversion
Example:
//Method 1: parselnt('28'); //There are decimal integers removed by default. Units can be automatically removed after values //Method 2: parseFloat('28.00'); //You can also go to units //Method 3: Number('28') //Method 4: '28'-0 // - * / can be converted to a numeric type
Other types convert to Boolean values
Boolean();
'', 0, NaN, null, undefined all convert to false
Others are converted to true
Special comparison operator
===: Equal, value and data type are required to be identical
!==:Inequality
Special Logical Comparison
Numeric logic comparison allows direct output of numeric values rather than Boolean values
Example:
console.log(123 && 456) // 456 console.log( 0 && 456) // 0 console.log(0 && 1+2 && 456) // 0
array
The js array can be stored without any data type.
Create by:
//Create a new empty array var Array name = new Array(); //Create an array using the array literal quantity var arr = []; //Array length var l = arr.length;
function
Encapsulates a piece of code that can be duplicated, equivalent to a method in java.
Declare method 1:
Function function function name (parameter) {
Function Body
}
Declare method 2:
var fn = function (parameter) {
Function Body
}
Execute directly with a function or method name call.
Function parameter parsing:
Parameters do not need to declare types. Declare parameter names directly
1. If the number of arguments and the number of formal parameters are the same, the corresponding reception, normal output results
2. If the number of arguments is the number of redundant parameters, the redundant parameters will be ignored and only the corresponding parameters will be received.
3. If the number of arguments is less than the number of parameters, parameters that are not received are considered unassigned variables, and the default value is undefined.
Example:
function getSum ( num1 , num2 ) { Function Body; } getSum( 1 , 2 ); // Normal call getSum( 1 , 2 , 3 ); // Parameter overflow, argument 3 not passed getSum( 1 ); // Missing a parameter, num2 is considered an unassigned variable with a value of undefined
break: results in the current loop
Continue: Jump out of this loop and continue with the next one
Return: Jump out of this loop and return the result to the caller. You can also end this method body
Built-in objects within functions:
arguments: which stores parameters passed in by the caller. Shown as a pseudo array that can be traversed
Pseudo-array features:
1. Has the length attribute
2. Store data indexed
3. push, pop, etc. without arrays
Example use:
function sinfi () { // View number of parameters var s = arguments.length; alert("Here comes"+s+"Parameters"); // Traversal parameters for(var i = 0; i < arguments.length; i++){ console.log("No."+(i+1)+"Parameters:"+arguments[i]); } } sinfi(28,86,34,38,22)
Variable Scope
A variable directly assigned to a function is not declared to be a global variable
Without block-level scope, declared variables in braces for () and if () are global variables. Only declared variables in functions are local variables.
1. Global variables will only be destroyed when the browser is closed, which takes up more memory
2. Local variables are destroyed when the program is finished, saving memory resources
Pre-parse
The js engine runs js in two steps: pre-parsed code execution
1. The pre-parsing js engine will promote all var s and function s in js to the top of the current scope
2. Code execution is performed from top to bottom in the order in which the code is written
The var and function declarations are precompiled into memory, with only the variable names and no assignments.
// Code 1: fun(); var fun = function() { console.log(22); } // Running will cause errors // Equivalent to running a bit of code var fun; fun(); fun = function() { console.log(22); } // Code 2: console.log(num); // Result: undefined, output unassigned variable var num = 10; // Equivalent to running the following code var num; console.log(num); num = 10;
Pre-parsing is divided into variable pre-parsing (variable promotion) and function pre-parsing (function promotion)
1. Variable promotion means that all variable declarations are promoted to the top of the current scope without raising the assignment operation
2. Function promotion means that all function declarations are promoted to the top of the current scope without calling a function
Practice:
var num = 10; fun(); function fun() { console.log(num); // Result: undefined var num = 20; } //The precompiled code is as follows var num; function fun(){ var num; console.log(num); num = 20; } num = 10; fun();
object
Method 1 for creating objects:
// Create object {} using object literals: object body inside curly brackets var obj = { uname : 'Zhang Sanfen', age : 18, sex : 'male' , sayHi : function() { Function Body } } // Call: directly by method. property name or function call obj.sayHi();
1. Object's attributes and attribute values are declared as key-value pairs. Key attribute name: Value attribute value
2. Multiple attributes or methods separated by commas
3. The method colon is followed by an anonymous function
Create Object Method 2:
// Creating Objects with new Object var obj = new Object(); // Create an empty object //Use the object name directly. The name of the property or function to be created is equal to the declaration and assignment obj.uname = 'Zhang Sanfen'; obj.age = 18; obj.sex = 'male'; obj.sayHi = function() { // Function Body console.log('hi~'); } // Call the method as above
Create Object Method 3:
// Constructor Create Object function Star() { this.name = uname; this.age = age; this.sex = sex; this.sing = function(sang){ console.log(sang); } } // Create two different objects var ldh = new Star('Lau Andy',18,'male'); ldh.sing('Ice and rain'); // Call and Pass Value var zxy = new Star('Jacky Cheung',19,'male'); //Called the same way //1. Capitalize the first letter of the constructor name //2. Our constructor does not need to return to return the result
Traversing object property content
Example:
// Create an object var obj = { name : 'uname', age : 18, sex : 'male', sing : function(sang){ console.log(sang); } } // Traversing Object Properties and Methods for(var k in obj){ console.log(k); // k Output is all property and method names console.log(obj[k]) // Key-Value Attribute Name and Value Function Name and Function Body in Output Object } // Result uname uname age 18 sex male sing function sing(sang)
Browser Pop-up Window
Differences and connections between alert(), confirm(), prompt():
Warning box alert()
Alert is a warning box with only one button "OK" and no return value. Warning boxes are often used to ensure that users can get some information. When a warning box appears, users need to click the OK button to proceed. Syntax: alert("text")
Confirmation box confirm()
Confirmation is a confirmation box, two buttons, confirm or cancel, and returns true or false. Confirmation boxes are used to enable users to verify or accept certain information. When a confirmation box appears, the user needs to click the OK or Cancel button to continue. If the user clicks Confirmation, the return value is true. If the user clicks Cancel, the return value is true.Syntax: confirm("text")
prompt()
A prompt is a prompt box that returns the entered message, or its default value prompt box is often used to prompt the user to enter a value before entering the page. When the prompt box appears, the user needs to enter a value and then click the Confirm or Cancel button to continue the operation. If the user clicks Confirm, the return value is the value entered. If the user clicks Cancel, the return value is the value entered.Syntax: prompt("text", "default")
Built-in Objects
There are three types of objects in javaScript: custom objects, built-in objects, and browser objects.
Built-in objects: Some of the objects that come with the js language for developers to develop.
javaScript provides several built-in objects: Math, Date, Array, String, and so on
All built-in objects can be found in the document for usage
File:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript
getRandom (a,b): Randomly generate an integer from a to B
Array :
instanceof operator It can be used to detect if it is an array
Array.isArray (parameter) is used to detect if it is an array
example
// Detection Array Method 1: var arr = [1,2,3]; if(arr instanceof Array) // Detect Array Method 2: console.log(Array.isArray(arr)); // Return true or false
Array Add Delete Element
Push (parameter 1...): add one or more return values at the end: new length
pop(): delete the last element of the array, reduce the length of the array by 1 return value: deleted element
Unshift (parameter 1...): add one or more elements to the beginning of the array return value: new array length
shift(): Delete the first element of the array, return value of array length minus 1: Deleted element
Array.reverse(): Flip the array
Array.shrt(): Array sorting:
// Can only rank numbers less than 10, if 11, according to the first number var arr1 = [13,4,77,1,7]; arr1.sort(); // Improve so he can sort all numbers arr.sort(function(a,b){ //return a - b;Sort ascending return b - a; //Sort in descending order });
indexOf("element"): Find the position of an element in an array and return -1 if no element is found
Array weighting:
function unique (arr) { var newArr = []; for(var i = 0; i < arr.length; i++){ if(newArr.indexOf(arr[i]) === -1 ){ //Add a new array without this element newArr.push(arr[i]); } } return newArr; } var demo = [1,5,4,3,1,4,6]; console.log(unique(demo));
Array Conversion String
Array.toString(): Converts an array to a string, with each element separated by a sign
Array.join("custom separator"): Converts an array to a string, separated by a number, which can be customized by default.