1. Operators
1 Post Operator
var num = 1; num += 1; num -= 1; //Pre-operator, plus first ++num; ++num; console.log(num); // ++ num prefix increases first and then outputs // num++ post-auto-increment first outputs in plus 1, returning the original value first, then adding 1 console.log('+++++++++++++'); var age = 11; // console.log(++num + 10); // This is equivalent to num = 22 // age++ post-auto-increment first output at plus 1, returns the original value 11 first, then auto-increment 1 equals 12 console.log(age++ + 10); console.log(age);
2 Comparison Operators
console.log(19 = '19'); //Judgment. Output true, default conversion data type, converts character type to number type console.log(19 === '19');//All equal. Output flase requires complete equality of type values
3. Logical Operators
&Logic and, ||Logic or,! Logical not
Priority of &&>| or, if present, precede &&
console.log(!false); //Output ture
3-1. Short Circuit Operator
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-FwXN2vSz-16421802485) (E:\Front End HTML, cssJavaScriptjavascript Notesimage-20213103818170.png)]
console.log(0 && 456);//Expression 1 is a false return expression 1 // If empty or negative is false, it is true 0''null undefined NaN
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save pictures and upload them directly (img-8khjxd2X-16421802486) (E:Front End HTML, cssJavaScriptJavaascript Notes3.4 Logical Interruption)]
Logical or Operator||Returns expression 1 if the result of expression 1 is true and expression 2 if the result of expression 1 is false
Tip: No True, No False
4. Conditional Branch Statement
4.1. Multi-Branch Statement
if(Conditional expression 1){ // Execute statement 1 }else if(Conditional expression 2){ // Execute statement 2 }else if(Conditional expression 3){ // Execute statement 3 }else{ // Last Statement }
4.2. Ternary expression
// Syntax structure: conditional expression? Expression 1: Expression 2 // Returns expression 1 if the conditional expression is true, otherwise returns expression 2 var num = 10; var result = num > 3 ? 'Yes' : 'No' console.log(result);
4.3 switch branch statement
switch(Expression){ case value1: Execute statement 1; break; case value2: Execute statement 2; break; ... default: Execute the last statement; } switch(5){ case 3: console.log('This is 3'); break; case 2: console.log('This is 2'); break; case 1: console.log('This is 1'); break; default: console.log('No value to output'); } // Note that num requires all equal to 1 var num = 3; switch(num){ case 1: console.log('This is 3'); break; default: console.log('No such value'); }
Note: num requires all equal to 1 num===1
//switch for fixed value and if else if for range value
5. Cycle
5.1 for loop
Note: Outer loops are rows and inner loops are columns
// For (initialization variable; conditional expression; operation expression){ // Circulatory body //Double for Loop Syntax Structure Outer Loop One Inner Loop All //Outer loop is row and inner column for(Outer Initialization Variables;Outer conditional expression;Outer Operational Expression){ for(Initialization variables for the layer;Inner conditional expression;Inner Operational Expression){ // Grammatical Structure } } // Print Five Lines Center var str = ''; for(var x=1; x<=5; x++){ for(var y=1; y<=5; y++){ str = str + '❤' } // Line break after printing str = str + '\n' } // Results to be output outermost console.log(str);
5.2 while Loop
//Grammatical Structure var str = ''; var num = 1; while(num <=100){ str = str + 'Hello'; num++; str = str + '\n' } console.log(str);
5.3 do...while
var sum = 0; var j=1; // Execute once, in a judgement loop do{ sum = sum + j; j++; }while(j <= 100) console.log(sum);
5.4 continue,break
- Continue keyword, exit the current cycle, continue the cycle number
- break exits the loop directly
// 1. Find a number that divides 1-100 by 7 for(var i=1; i<=100; i++){ if(i % 7 !== 0){ continue; } console.log(i); // Within the circulation is the result of each cycle, and outside the circulation is the result. } // The following line of code will not execute until the loop ends // console.log(i);
6. Arrays
Array array: An elegant way to store a collection of data in a single variable
var array name= []
var arr = [1,2,'pink',true]; // Get array element, number name [index number] console.log(arr[2]);
6.1 traversal
To access each element from beginning to end, you must start at 0
var arr = ['Sunday','Tuesday','pink',2] // arr.length statistical array length for(var i = 0; i < arr.length; i++){ console.log(arr[i]); }
Case 1 Calculated Average
var arr= [1,4,5,6,7]; var sum=0; var average = 0; for(var i = 0; i<arr.length; i++){ sum += arr[i]; //We add the array element arr[i] instead of the counter I } average = sum / arr.length; console.log(average); //Question 2 Finding the Maximum in an Array var arr = [2,44,3,5,8,33]; // Set a value first var max = arr[0]; for(var i = 1; i<arr.length; i++){ //Determine the maximum, which is passed to max if(arr[i] > max){ max = arr[i]; } } console.log('Maximum value is'+max);
String concatenation requires an s t r ='';
6.2 Array Append Modification
var arr = ['green','red','black'] console.log(arr); arr[3] = 'brown' console.log(arr); //Append Array Elements arr[1] = 'white' //Modify Array Elements console.log(arr); // Question 2 Store numbers greater than 10 in a new array var arr = [11,2,33,44,5,66,7,23]; var new_arr = []; // Declare a variable to add a storage array each time var j = 0; for(var i=0; i<arr.length; i++){ if(arr[i] > 10){ // The index number of the new array must start at 0 new_arr[j] = arr[i]; // j+1 stored at a time j++ } } console.log(new_arr); //Method 2 new_ Arr[new_arr.length] = arr[i]; var arr = [11,2,33,44,5,66,7,23]; var new_arr = []; for(var i=0; i<arr.length; i++){ if(arr[i] > 10){ // The index number of the new array must start at 0 new_arr[new_arr.length] = arr[i]; } } console.log(new_arr); // Question 3 Reverse output array var arr = ['red','green','black','white']; var newArr = []; // Total length minus one is the last start output arr.length-1 for(var i=arr.length-1; i>=0; i--){ newArr[newArr.length] = arr[i]; } console.log(newArr);
6.2.1 Bubble Sorting Case
1. Bubble sleeve: An algorithm for displaying a series of data in a certain order (from small to large or from large to small). Compare two elements at a time and exchange them if the order is wrong.
// Total number of trips we use outer loop // For each swap, we use the inner loop, lenght-i-1 var arr = [5,4,3,2,1,6]; // Outer layer only loops arr.length-once for(var i=0; i<arr.length-1; i++){ for(var j=0; j<arr.length-i-1; j++){ if(arr[j] > arr[j+1]){ var temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } console.log(arr);
7. Functions
function Function name(Formal parameter 1,Formal parameter 2,...){//Formal parameter to receive misfortune } Function name(Argument 1,Argument 2,..) //Actual parameters // Case 1 // A function encapsulates a block of code that is reread to perform Commission function getSum(num1,num2){ var sum = 0; for(var i=num1; i<=num2; i++){ sum += i } console.log(sum); } getSum(1,100);
7.1 Function Return Value
function Function name(Formal parameters){ return Result to be returned; } Function name(); //caller // (1) Our function only implements a function, and the end result needs to be returned to the caller's function name () through return // (2) Return the following result to the caller's function name () = the result after return only if the function encounters return // case function getReturn(){ return 666; } getReturn(); //getReturn() = 666 console.log(getReturn());
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-kL6MQMU-16421802487) (E:Front End HTML, cssJavaScriptjavascript NotesFunction return.png)]
Return num1 + num2 to getSum(1,2)
[External chain picture transfer failed, source may have anti-theft chain mechanism, it is recommended to save pictures and upload them directly (img-bBUZVhJM-16421802487) (E:Front End HTML, cssJavaScript\javascript NotesFunction return2.png)]
// Summation function getSum(num1,num2){ return num1 + num2; } console.log(getSum(1,4)); //Is return num1 + num2 returned to getSum(1,4) //getSum(1,4) = num1 + num2 while num1 and num2 are 1,4, respectively // Case 2 uses a ternary expression to return function getMax(num1,num2){ return num1 > num2 ? num1:num2; } console.log(getMax(11,22)); console.log(getMax(11,2)); // Case 3 Maximum arr in evaluation array = [2,33,44,55,5,66,77] function getArrmax(arr){ var max = arr[0]; for(var i=1; i<arr.length; i++){ if(arr[i] > max){ max = arr[i]; } } return max; } var result = getArrmax([2,33,44,55,5,66,77]) console.log(result); //Primitives: Numbers other than 1 and itself that can be integer divisible (0, 1 are not primitives) //Refers to a number in a natural number greater than 1 that cannot be divided by any other natural number except 1 and the number itself (also defined as a number with only two factors of the number itself) var num = parseInt(prompt('Please enter a number:')); for( var i = 2; i<num; i++){ if(num % i ==0){ // An explanation that can be divided by an integer is not a prime number alert('Not a prime number'); break; }else{ alert('Yes is a prime number'); break; } }
Note: return terminates the function and returns only one value
7.2 arguments pseudo array
[External chain picture transfer failed, source may have anti-theft chain mechanism, it is recommended to save pictures and upload them directly (img-956Vixv8-16421802488) (E:Front End HTML, cssJavaScriptjavascript NotesPseudo Array.png)]
//Case 3 Judging Leap Year function isRunYear(year){ var flag = false; if(year % 4 == 0 && year % 100 !=0 || year % 400 == 0){ flag = true; } return flag; } var result = isRunYear(2000); console.log(result);
Calling functions within 7.3 functions
// User Enter Year, Output Days of Current February function Day(){ var yearDay = parseInt(prompt('Please enter a year:')) // Call a function to determine leap years if(isRunYear(yearDay)){ alert('It is a leap year with 29 days in February'); }else{ alert('Not leap year, February 28 days'); } } Day() //Functions for Judging Leap Years function isRunYear(year){ var flag = false; if(year % 4 == 0 && year % 100 !=0 || year % 400 == 0){ flag = true; } return flag; }
7.3.1 Anonymous Functions
var Variable Name = function(){} var fun = function(){ console.log('I am an anonymous function'); } fun()
8. Scope
//Global Scope: entire script tag or a single js file
//Local scope (function scope) is local within a function
//Similarly, there are global changes
<script> // Global scope: entire csript tag or a single js file // Local scope (function scope) is a local scope within a function // global variable var num =10; function fnPart(){ // Local variables, within a function, do not interact with global variables var num = 10; } </script>
9. Pre-parsing
1. Our js engine runs js in two steps: pre-parsed code execution
2. The pre-parsing js engine will promote var and function inside js to the top of the current scope
3. Code execution is written from top to bottom
4. Variable promotion means that all variable declarations are promoted to the top of the scope
// Equivalent to the following code var a ;//Put global variables first function f1(){ var b; var a; b = 9; console.log(a); console.log(b); a = '123'; } a = 18; f1();
10. Objects
1. Class is an abstract concept that does not exist in real time/space. Class only defines abstract properties and behaviors for all objects. Like Person, it can contain many individuals, but it does not exist in the real world.
2, the object is a concrete of the class. It is a real thing.
3. Classes are a static concept and do not carry any data. When no object is created for the class, the class itself does not exist in memory space.
4. Object is a dynamic concept. Each object has its own unique attributes and behaviors that are different from other objects. An object's properties can change as it behaves.
(The object is specific, such as Xiao Ming's notebook computer, which is real)
10.1 What are objects, attributes, methods
[External chain picture transfer failed, source may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-X3Qql7L9-16421802489) (E:Front End HTML, cssJavaScriptjavascript NotesObject.png)]
10.2 Create Objects
// Literal Create Object {} var obj ={}; //Create an empty object var obj ={ // Build attribute names using key-value pairs: value attribute values name:'Zhang San', age:'18', sex:'male', // Creation Method sayHi:function(){ console.log('hi~'); } } // Use object, object name. Property Name console.log(obj.name); // Method 2 console.log(obj['age']); // Call object's method sayHi object name. Method () obj.sayHi()
Create Object Method 2
// Creating Objects with new Object var obj = new Object(); // Add object properties and methods using'='assignment obj.uname = 'Zhang Sanlun'; obj.age = 17; obj.sex = 'male'; // Create methods to add object properties and methods using'='assignment obj.sayHi = function(){ console.log('hi!'); } // Call Method console.log(obj.uname); console.log(obj.sayHi());
10.3 Constructor
function Constructor name(){ this.attribute = value; this.Method = function(){ } } // call new Constructor name(); //The first letter of the constructor name needs to be capitalized Star //for example //Constructor star refers to a broad category function Star(uname,age,sex){ this.name = uname; this.age = age; this.sex = sex; this.sing = function(song){ console.log(song); } } //Object refers specifically to a specific thing var Man = new Star('Xiao Ming',18,'male') // console.log(Man); console.log(Man.name); var Man2 = new Star('Xiao Ming 2',218,'2 male') console.log(Man2.sex); // console.log(Man.sing()); Man2.sing('Into Concert song'); // console.log(Man2.sing()); //The process by which we create objects with functions is also called instantiation of objects
Case 1
function Wzhonour(uname,type,blood,attack){ this.name = uname; this.type = type; this.blood = blood; this.attack = attack; this.technique = function(skill){ console.log(skill); } } // Generate two objects, pass in // new Wzhonour('descendants','strength','500','melee'); To call a function, you must add new var houyi = new Wzhonour('Offspring','Strength type','500','Civil War'); var lianpo = new Wzhonour('Cheap Po','Sagittarius','100','Long-range'); console.log(houyi.name); console.log(houyi['type']); houyi.technique('sunlight'); console.log(houyi.technique());
Execution steps:
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-8fg1reaA-16421802489) (E:Front End HTML, cssJavaScriptjavascript Notes new object.png)]
10.4 Traversing Objects
// Method; For (variable in object) { // } var obj = { name : 'millet', age : '19', sex : 'male' } //key value key-value pairs for(var k in obj){ console.log(k);//Output is attributes console.log(obj[k]); //Output value }
11. Built-in Object method
// javascript provides several built-in objects: Math Date Array String, which is math, date, array, string, etc.
Refer to Document Address: https://developer.mozilla.org/zh-CN/docs/Web
Case: Use object to encapsulate own mathematical object to get maximum and minimum value, argument is a pseudo array, see the introduction
//Complex data type Math Date Array String
// javascript provides several built-in objects: Math Date Array String, and so on // console.log(Math.max(1,3,44,5)); // argument is a pseudo array. See the description var myMath = { Pi : 3.141592653, // Definition method max : function(){ // Define a maximum value to get pseudo elements starting at 0 var max = arguments[0]; for(var i=1; i<arguments.length; i++){ if(arguments[i]>max){ max = arguments[i] } } return max; },//Note that this needs to be added, separated by numbers // Method for Defining a Minimum Value min : function(){ // Using a pseudo array, create a min comparison, starting at 0 var min = arguments[0]; for(var i=1; i<arguments.length; i++){ if(arguments[i]<min){ min = arguments[i]; } } return min; } } console.log(myMath.Pi); console.log(myMath.max(1,2,3,4,5,44)); console.log(myMath.min(2,3,4,1,0));
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-lGd0mjc6-16421802490) (E:Front End HTML, cssJavaScriptjavascript Notes math method.png)]
11.1 Random method Math.random()
Returns a random decimal range of 0 <= random <1 [excluding 1)
Gets a random integer between two numbers, inclusive function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; //With maximum and minimum }
11.2Date Date object
The Date() Date object is a constructor and must be called with new to create our date object
// The Date() Date object is a constructor and must be called with new to create our date object var obj = new Object();//Create an object instance var arr = new Array();//Create an array object var date = new Date(); console.log(date); //case var date = new Date(); var year = date.getFullYear(); var arr = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; var day = date.getDay(); console.log(arr[day]); //Sunday is 0 console.log(date); console.log(date.getFullYear()); //Case 2 // Setting time using functions function getTime(){ var time = new Date(); var h = time.getHours(); // The ternary rule determines if h is less than 10 and then zero-filling, +h otherwise outputs h directly 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());
Countdown cases: key cases written three times
[External chain picture transfer failed, source may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-N1hwtUX-16421802491) (E:Front End HTML, cssJavaScript\javascript NotesCountdown.png)]
//+ new Date() returns milliseconds that need to be converted to seconds function countDown(time){//Time entered by the user var nowTime = + new Date();//Return to the current time, returning milliseconds var inputTime = + new Date(time);//Time entered by the user var times = (inputTime - nowTime ) / 1000;//Total seconds remaining var d = parseInt(times /60 /60 /24); //day d = d<10? '0'+d :d; var h = parseInt(times /60 /60 % 24); //hour h = h<10? '0'+h :h; var m = parseInt(times /60 %60);//Minute m = m<10? '0'+m :m; var s = parseInt(times % 60);//second s = s<10? '0'+s :s; return d+'day'+h+'hour'+m+'branch'+s+'second'; } console.log(countDown('2021-12-20 18:00:00'));
11.3 Reference Array Method
11.3.1 Judgement Array
function reserve_arr(arr){ if(Array.isArray(arr)){// if(arr instanceof Array) determines if it is an array arr instanceof Array var new_arr = []; for(var i=arr.length-1; i>=0; i--){ new_arr[new_arr.length] =arr[i]; } return new_arr; }else{ return '"erro Not an array"' } } var isArr = reserve_arr([1,2,3,4,5]); console.log(isArr); console.log(reserve_arr(1,2,3)); // var arr = [1,2,3]; var not_arr = (1,2,3); // console.log(Array.isArray(arr)); //Determine if it's an array console.log(Array.isArray(not_arr)); console.log(not_arr instanceof Array);
11.3.2 Addition and deletion of search arrays
// 1.push adds an array at the end var arr = [1,2,3,4] arr.push(4,'pink'); console.log(arr); //2.unshift adds an array before arr.unshift('red'); console.log(arr); // 3.pop() deletes the last element arr.pop() console.log(arr); // 4.shift() deletes the first element arr.shift() console.log(arr); // Case 1 salary_arr = [2000,1400,200,300] append to new array with less than 2000 var salary_arr = [2000,1400,200,300]; // New Array var newArray = []; for(var i=0; i<salary_arr.length; i++){ if(salary_arr[i]<2000){ // Add from behind, salary_arr[i] represents the size of the number newArray.push(salary_arr[i]); } } console.log(newArray); //Case 2 Flip Array var reArr = [1,2,3,4,5]; reArr.reverse() console.log(reArr); //Case 3 Bubble Sorting var arr1 = [1,13,3,14,5,2]; arr1.sort(function resort(a,b){ //The resort function name can be arbitrarily named // return a-b //ascending return b-a //Sort in descending order }) console.log(arr1);
11.3.3 Get array index, array object
//indexOf returns the index number of the array, lastindexOf looks backwards and forwards var arr = ['blue','red','green','blue','pink'] var arrindex = arr.indexOf('blue') console.log(arrindex);
Case: Array Unweighting
Note: often misspelled length
// Case Array Weighting, ['a','b','c','a','g','a','b'] function unique(arr){ var new_arr = []; for(var i=0; i<arr.length; i++){ if(new_arr.indexOf(arr[i]) === -1){//=== -1 is the new array without that element new_arr.push(arr[i]); } } return new_arr; } var demo = unique(['a','b','c','a','g','a','b']); console.log(demo); //toString() converted to string var arr = ['blue','red','green','blue','pink'] // join to string console.log(arr.join('&')); console.log(arr.join());
11.4 String Object
var str = 'The village wind blows'; console.log(str.indexOf('wind',2));//Search from the second // Case 1, Find all the letters o'abcfoddossoero' var str = 'abcfoddossoero'; var index = str.indexOf('o'); var num = 0; // console.log(index); while(index != -1){//index loops as long as it is not equal to -1, -1 means there is no such element\ num++; console.log(index); index = str.indexOf('o',index+1);//Find o's index, index+1, continue looking later //!! For example, the first index+1 is to continue searching from index 5 and assign it to the index. //index=7, and 7!= - 1, continue executing code, continue looking for'o', now index is 7, index+1~Start at index 8 } console.log('o Number of occurrences'+num);
Gets the number of occurrences of the array, and the position
// ['red','blue','red','green','pink','red','white'], find the number and location of red occurrences var arr = ['red','blue','red','green','pink','red','white']; var index = arr.indexOf('red'); // console.log(index); var num = 0; while(index != -1){//Not equal to -1 to continue getting console.log(index); num++; index = arr.indexOf('red',index+1);//Continue fetching from index+1 and get the assignment to index } console.log('frequency'+num);
11.4.1 Returns a character based on its position
//Returns the character str.charAt() based on its position var str = 'andy'; var index = str.charAt(3); console.log(index); for(var i=0; i<str.length; i++){ console.log(str.charAt(i)); } //Method 2 str[index] Gets the character at the position var str = 'andyrrr'; console.log(str[4]); // str.charCodeAt(index) Gets the ASCll code for the character at the specified location console.log(str.charCodeAt(0));
Other methods
//substr('intercept starting position','intercept several characters') var str1 = 'Reforming the Spring Wind'; console.log(str1.substr('2','2')); // Replace str3 ='sadosaofdsoo', o with * var str3 = 'sadosaofdsoo'; // var index = str3.indexOf('o');// Index for o // console.log(index); while(str3.indexOf('o') != -1){//Replace'0'with * Continue looping as long as'o' is not equal to -1 str3 = str3.replace('o','*'); } console.log(str3); //Converts a character to an array split('delimiter') var str4 = 'red,pink,blue'; console.log(str4.split(',')); var str4 = 'red&pink&blue'; console.log(str4.split('&'));
var index = str.charAt(3);
console.log(index);
for(var i=0; i<str.length; i++){
console.log(str.charAt(i));
}
//Method 2 str[index] Gets the character at the position var str = 'andyrrr'; console.log(str[4]); // str.charCodeAt(index) Gets the ASCll code for the character at the specified location console.log(str.charCodeAt(0));
Other methods ```javascript //substr('intercept starting position','intercept several characters') var str1 = 'Reforming the Spring Wind'; console.log(str1.substr('2','2')); // Replace str3 ='sadosaofdsoo', o with * var str3 = 'sadosaofdsoo'; // var index = str3.indexOf('o');// Index for o // console.log(index); while(str3.indexOf('o') != -1){//Replace'0'with * Continue looping as long as'o' is not equal to -1 str3 = str3.replace('o','*'); } console.log(str3); //Converts a character to an array split('delimiter') var str4 = 'red,pink,blue'; console.log(str4.split(',')); var str4 = 'red&pink&blue'; console.log(str4.split('&'));