catalogue
Basics:
It is divided into ECMAScript (standardized programming language), DOM (document object model) and BOM (browser object model)
Written form:
1. Inline
<input type="button" value="Ah, ah" onclick="alert('Ah, ah, ah, ah')">
2. Embedded JS
<script> alert('Ah, ah'); </script>
3. External JS files
<script src="my.js"></script>
Notes: / / (Ctrl + /) and / * * / (Shift+Alt+A)
Basic input / output:
alert(msg) | Browser pop-up alert box | browser |
console.log(msg) | Browser console printout information | browser |
prompt(info) | The browser pops up an input box, which can be entered by the user | browser |
Variable:
1. Declare variables: var age //var is the JS keyword used to declare variables
2. Assignment
Initialization = declaration + assignment.
The unassigned value is undefined.
data type
JS is a weakly typed language; Is a dynamic language, and the data types of variables can be changed.
Data type: simple data type (Number, Bollean, String, Undefined, Null), complex data type (object, Array, Date, etc.).
Complex data types are created using the new keyword.
Number: the number preceded by 0 indicates octal; Plus 0x indicates hexadecimal.
console.log(Number.MAX_VALUE); //1.7976931348623157e+308 console.log(Number.MIN_VALUE); //5e-324 console.log(Infinity); //Infinity infinity console.log(-Infinity); //-Infinity infinitesimal console.log(NaN); //A non numeric value isNaN //Judge whether it is a number, return false if it is a number, and return true if it is not a number.
String: single quotation marks are recommended. Using the nesting relationship of quotation marks, the outer double inner single or outer single inner double.
\n | Newline character |
\\ | Slash\ |
\' | Single quotation mark |
\" | Double quotation mark |
\t | tab indent |
\b | Space |
var str = 'Ah, ah'; console.log(str.length); //Detects the length of the output string console.log('abab'+srt); //String splicing console.log(srt+18); //String splicing var age = 18; console.log(srt+age); //String splicing console.log('12'+18); //String splicing '1218'
Boolean: can directly participate in the operation.
Undefined: if the variable is not assigned a value, it is undefined.
var str = 'Ah, ah'; var ariable = undefined; console.log(variable+srt); //undefined console.log(variable+1); //NaN
Null
var str = 'Ah, ah'; var space = null; console.log(variable+srt); //Come on, come on console.log(variable+1); //1
Get data type typeof
var num=10; console.log(typeof num); //number var str='abab'; console.log(typeof str); //string var flag=true; console.log(typeof flag); //bollean var vari=undefined; console.log(typeof vari); //undefined var timer=null; console.log(typeof timer); //object
Data type conversion
toString() | Convert to string | var num = 1; alert(num.toString()); |
String() | Convert to string | var num = 1; alert(String(num)); |
Plus concatenated string | And string splicing results are strings | var num = 1; alert(num + "string"); |
parseInt(String) | string to integer value (round down and automatically remove the unit letter (such as px)) | parseInt('78') |
parseFloat(String) | string to floating point number value (unit letters (such as px) are automatically removed) | parseFloat('78.21') |
Number() | string to numeric | Number('12') |
js implicit conversion (- * /) | Use arithmetic operation to implicitly convert to numerical type | '12' - 0 '12' * 1 '12' / 1 |
Boolean() | Convert other types to boolean | Boolean('') |
console.log(Boolean('')); //false console.log(Boolean(0)); //false console.log(Boolean(NaN)); //false console.log(Boolean(null)); //false console.log(Boolean(undefined)); //false console.log(Boolean()); //All others are true
JS: explanatory language; Java: compiler language
operator
Arithmetic operator
Increment decrement operator
Comparison operator
!== And = = = indicate congruence, and the required values and data types are consistent
Logical operator
Assignment Operators
priority
Parentheses > unary operator > arithmetic operator > relational operator > equality operator > logical operator > assignment operator > comma operator
Process control
order
if judgment
Ternary expression
Conditional expression? Expression 1: expression 2
switch branch
loop
array
Create array:
1. Create an array using new; 2. Use array literal to create an array
Any type of data can be placed in the array
var arr = new Array(); //1. Create an array with new var arr = []; //2. Use array literal to create an array var arr = [1,2,'abab',true];
Get element: index
console.log(arr); //Array(4) console.log(arr[2]); //abab
Find array length
console.log(arr.length);
Add array element
var arr = [1,2,'abab',true]; arr.length = 7; //1. Modify array length console.log(arr[4]); //undefined arr[4] = 'ababab'; //2. Add array elements
function
1. Declare function, 2 Call function
function Function name(){ //statement Function body; } function Function name(Formal parameter 1, formal parameter 2){ Function body; } Function name(); //call Function name(Argument 1, argument 2);
If the number of arguments is more than the number of formal parameters, only the first few are taken; If the number of arguments is less than the number of formal parameters, multiple formal parameters are defined as undefined.
If the function does not return, it returns undefined
Use of arguments: the arguments object stores all arguments passed. Arguments is a pseudo array, which has the following characteristics: 1 With length attribute; 2. Store data in index mode; It does not have array push, pop and other methods.
There are two ways to declare functions:
function fun(){ } var fun = function(){ //fun is the variable name, not the function name. The function is stored in the variable }
Scope
Global scope: the entire script tag or a separate js file. Note: the variables assigned but not declared inside the function are also global variables; Formal parameters can also be regarded as global variables.
Local scope: inside a function
Block scope: not before es6.
Scope chain: small domains can access large domain variables. Chained lookup access mechanism.
JS pre parsing
The JavaScript parser runs JavaScript code in two steps: pre parsing and code execution.
1. Pre parsing will promote all var and function s in js to the front of the current scope.
2. Code execution: execute from top to bottom according to the code writing order
3. Pre parsing is divided into variable promotion and function promotion. Variable promotion: all variable declarations are mentioned first, and the assignment operation is not promoted. Function promotion: promote all function declarations to the front without calling functions.
object
Object: an unordered collection of related properties and methods.
Attributes: characteristics of things. Method: thing behavior.
Create object: 1 Create objects with literal values; 2. Create an object using new Object; 3. Create objects using constructors.
Constructors are capitalized. Constructors are similar to class es. The process of creating objects with constructors is also called instances of objects.
//1. Object literal creation object: {} var obj = { uname: 'abab', //Property uses key value pairs age: 18, //Comma separated sex:'man' sayHi: function(){ //Method colon followed by an anonymous function console.log('abab'); } } console.log(obj.uname); //Call: object name Property name. console.log(obgj['age']); //Call: object name ['property name']. obj.sayHi(); //Call: object name Property name. //2. Create an object using new Object var obj = new Object(); obj.uname = 'abab'; //Add object properties and methods by assigning values with the = equal sign obj.age = 18; obj.sex = 'man'; obj.sayHi = function(){ console.log('abab'); } //3. Create object by constructor function Constructor name(){ this.attribute = value; this.method = function(){} } new Constructor name(); //example function Person(uname,age,sex){ //The constructor is capitalized, and return is not required this.name = uname; this.age = age; this.sex = sex; } var me = new Person('abab',18,'man'); //create object console.log(me.name); //use console.log(me.age);
new process:
1. Create a new object in memory
2.this points to an empty object
3. Point to the function code and add properties and methods for empty objects
4. Return this object
Traversal object: for The in statement can loop through the attributes of arrays and objects.
for(var k in obj){ console.log(k); //k variable to get the attribute name console.log(obj[k]); //obj[k] output attribute value }
JS built-in object
JS object: custom object, built-in object, browser object (JS API).
Document: MDN: http://developer.mozilla.org/zh-CN/
Math
Math} is not a constructor. All attributes and methods of math} are static.
Common:
Math.max();
Math.abs(): absolute value;
Three rounding methods: math Floor () (rounded down); Math.ceil() (rounded up); Math.round() (round)
Math.random(): returns a random decimal [0,1].
Date
Create a JavaScript Date instance that renders a certain time in time.
var date = new Date(); //Created a Date console.log(date); var date1 = new Date(2019,10,1); var data2 = new Date(2019-10-1 8:8:8); console.log(date1); //Fri Nov 01 2019 00:00:00 GMT+0800 (China standard time) console.log(date2); //Report a bug /* new Date(); new Date(value); Common writing method of parameters: numeric type: 2019, 10, 01 new Date(dateString); String type: '2019-10-01 8:8:8' It is strongly discouraged to use the Date constructor to parse Date strings new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]); */
method:
getFullYear() | Get current year |
getMonth() | Get current month (0-11) |
getDate() | Get the current number |
getDay() | Get the current day of the week (day: 0 - Saturday: 6) |
getHours() | Get current hour |
getMinutes() | Gets the current minute |
getSeconds() | Gets the current second |
//Get the number of milliseconds (time stamp) of Date from January 1, 1970: var date = new Date(); //1 console.log(date.valueOf()); console.log(date.getTime()); //2 var date1 = +new Date(); concole.log(date1); //3 H5 NEW concole.log(Date.now());
Case: Countdown:
function countDown(time) { var nowTime = +new Date(); //Current milliseconds var input = +new Date(time); //Enter the number of milliseconds for the time var times = (input - nowTime) / 1000; //Seconds of time remaining 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+'hour'+m+'branch'+s+'second'); }
Array object
Array is a kind of list object. Its prototype provides operations related to traversing and modifying elements.
Constructor to create an array:
var arr = new Array(); //Create an empty array var arr = new Array(2); //Create an array with a length of 2 var arr = new Array(2,3); //Create array [2,3]
Check whether it is an array:
//instanceof operator var arr = []; var obj = {}; console.log(arr instanceof Array); //true console.log(obj instanceof Array); //false //Array. Isarray() H5 new method console.log(Array.isArray(arr)); //true
Add delete method:
push() | Add one or more elements at the end to modify the original array | Returns the new length |
pop() | Delete the last element, reduce the length of the array by one, have no parameters, and modify the original array | Returns the value of the deleted element |
unshift() | Add one or more elements to the beginning of the array to modify the original array | Returns the new length |
shiift() | Delete the first element, reduce the length of the array by one, and modify the original array | Returns the value of the first element |
Reverse array: arr.reverse();
Bubble sort: arr.sort();
//Successful form of sort: arr.sort(function(a,b){ return a-b; //Ascending arrangement //return b-a; // Descending sort });
Array index:
indexOf() | Finds the first index of a given element in an array | If it exists, the index number is returned; If it does not exist, - 1 is returned |
lastIndexOf() | The last index in the array | If it exists, the index number is returned; If it does not exist, - 1 is returned |
To string:
toString() | Convert the array into a string, separating each item with a comma | Returns a string |
join('separator ') | Convert all elements in the array into a string | Returns a string |
other:
concat() | Connect two or more arrays without affecting the original array | Returns a new array |
slice() | Array interception slice(begin,end) | Returns a new array of intercepted items |
splice() | Deleting splice(begin,end) from the array will affect the original array | Returns a new array of deleted items |
String object
Basic wrapper types: wrap simple data types into complex data types.
The value of the string remains unchanged. It seems to change the content. In fact, it changes the address, and a new address space is opened up in memory.
Since all methods of the string will not modify the string itself, a new string will be returned after the operation is completed.
Return position according to character:
indexOf() | Finds the first index of a given character in a string | If it exists, the index number is returned; If it does not exist, - 1 is returned |
lastIndexOf() | The last index in the string | If it exists, the index number is returned; If it does not exist, - 1 is returned |
//str.indexOf('character to find ', [starting position]) var str = 'abcdfsda'; console.log(str.indexOf('a',3)); //Look back from where the index number is 3 //lastindexOf can also set the starting search position
Return characters according to position:
charAt(index) | Returns the character at the specified position |
cahrCodeAt(index) | Gets the ASCII code of the character at the specified position |
str[index] | Gets the character {H5 at the specified position |
Judge whether there is an attribute in the object: Object ['attribute name']
var o = { age: 18 } if(o['age']) {console.log('There is this attribute in it');} else {console.log('There is no such attribute in it');}
Case: get the characters that appear the most times in a group of strings:
//1. Get the character and its maximum value var str = 'fdfsafewfsdfwefadsaf'; var o = {}; for(var i = 0; i < str.length; i++) { var chars = str.charAt(i); if(o[chars]){ 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 and the attribute value is o[k] if(o[k] > max){ max = o[k]; ch = k; } } console.log(max + ' ' + ch);
Other operation methods of string:
concat(str1,str2,str3) | Connect two or more strings. Equivalent to ++ More commonly used |
substr(start,length) | Number of length when starting from start |
slice(start,end) | Starting from start, intercept the position of end, but end cannot |
substring(start,end) | Starting from start, intercept the position of end. End cannot get it and does not accept negative values |
replace('replaced character ',' replaced character ') | Replace the characters in the string, only the first character |
split('separator ') | Convert string to array |
toUpperCase() | Convert to uppercase |
toLowerCase() | Convert lowercase |
Data type memory allocation
Heap and stack
Simple data types are stored directly on the stack.
Complex data types first store addresses in the stack, and then this address points to the data stored in the heap.
Simple data type: when a function passes a parameter, a copy of the argument is copied to the formal parameter.
Complex data type: when a function passes a parameter, the actual parameter (address) is assigned to the formal parameter. Changing the value in the function will affect the original actual parameter.