JavaScrip Notes Experience (Continuous Update)

Introduction to JavaScript

1,JavaScript

1.1. Why learn JavaScript?

  • Verify user input
  • Effectively organize web content
  • Dynamic display of web page content
  • Compensate for features that static web pages cannot achieve
  • Animation Display

1.2. Introduction to JavaScript

  • JavaScript is an object-based scripting language originally designed and implemented by Netscape on its Navigator 2.0 product, formerly called Live Script. Syntax JavaScript is similar to programming languages such as C#, java
  • Javascript is a client-side scripting language, that is, it runs on the client's browser and does not require server support
  • JavaScript is an interpretive language whose source code does not need to be compiled before execution by the client. Instead, character code in text format is interpreted and executed by the browser on the client. That is, JavaScript requires browser support.

1.3. JavaScript Language Features

  • Scripting languages (cannot run independently and must be embedded in other languages, such as HTML)
  • Explanatory
  • For Clients
  • Object-based

    1.4. JavaScript Writing Specification
  • Place in the middle of...
  • Executed line by line, shorter is better
  • Case Sensitive
  • A statement is a basic unit and usually ends with a semicolon
  • A multiline statement can be used as a block, using {}
  • Use notes more often

1.5. Basic process of writing JavaScript

  1. layout
    HTML/ASP. NET+CSS
  2. attribute
    Determine which properties to modify
  3. Event
    Determine what the user does?
  4. To write
    In the event, use JavaScript to fulfill user requirements

Common Content

  • Fundamentals
//js statement can end with or without semicolons
  • Output Content to Page
document. write(Text Content)
document. write("news") ;   //This direct display on the page is less useful
console.log("news");       // This is more debugged after pressing F12
alert("news");           //This is a pop-up message
  • Insert a snippet here to pop up a warning box
alert(Text Content)
  • Input Statement
 prompt("Title ","Default Value"),Not recommended

2. How to use JavaScript

1. Write JavaScript code on a page. (Suitable for pages with less code and no other pages)

Usually in our html head Node Usage< script> </script>Included elements are javascript
<script type="text/javascript">
//Write JavaScript code
</script>

text

document.write("<b> This is a text.</b>");

Bounce window determination

alert("Determine");

Pop-up window cancelled for selection

confirm("Are you sure you want to delete it?");

2. Write JavaScript code as a stand-alone external file for use with a.JS extension

  1. Create HTML Page
  2. Create JS files and write JS code directly
  3. Save file in JS format
  4. Called in an HTML file with the < cript type="ext/javascript"'src=js file path"</ script statement.
< script type=" text/javascript"'src="js File Path"> </script> 

3. Core Composition of JavaScript

4. Code comments for Javascript

JavaScript single line comment

Single line comment to∥start,Open East with Line
 For example:
<script type="text/javascript>
//  Here is Note 1
/*  Here is Note 2  */
</script>

JavaScript multiline comments

Multiline comments to  /* Start with*/  End,The middle statement is a comment in the program
 for example
/*
    Author: Xie Chan Software
    Date: 2017-2-25
    Description: First Javascript trial page
*/

HTML Comments

CTRL+/
<!--  -->

5. Data type of Javascript

1. Basic data types

  • Numeric data type (number)
  • Boolean type
  • Undefined Data Type (undefined) Weak type features are ambiguous or define runtime exceptions when not used
  • Empty data type (nul)

2. Reference data type

  • String type (string)
  • Aray array type
  • Object Type
Use typeout Operators can view data types of variables

6. Declarations and assignments of variables

Declare variables before assigning values

var name; 
name="app Software";

Declare and assign variables simultaneously

var count 10;

Declare multiple variables, using commas

    var x,y,z=10;
perhaps var x=y=z=10;  /The difference is?
Both declare three variables,The former only assigns values to B;The latter assigns all values

Hybrid Computing Data Type

  • Integer and decimal = decimal
  • Integer and String=String
  • Integer and Boolean = Integer
  • Integer and Null = Integer
  • Decimal and String=String
  • Decimal and Boolean = Decimal
  • Decimal and Null = Decimal
  • String and Boolean=String
  • String and Null=String
  • Boolean and Null = Integer

Conversion of data types

Number(a)String Number
parseInt(a)Reshaping 89.6 Convert to 89 Non-numeric Automatic Load Bias 2008 a Actual conversion to 2008
parseFloat(a)Decimal

parseInt(String)

parseInt(String)
Converts a string to an integer number, rounding
parselnt("86.6")String "88.6"Convert to integer value 86

parseFloat(String)

parseFloat(String)
Converts a string to a floating-point number
parseFloat("34.-45")String"34.45"Convert to floating point value 34.45

7. Expressions and Operators

An expression is an operation on one or more variables or values (operands) and returns a new value

Operators can be grouped into the following categories:

  1. Assignment Operator=
  2. Arithmetic Operators +, -, *, /,%, ++, -, -(negation)
  3. Combination Operators*=, /=, +=, -=,%=
  4. Comparison Operator=,!=, >, >=,[, <=, ===,! ==
  5. Logical Operators &&, ||,!
  6. String Operation+

Absolutely equal: data types are the same, values are equal===
Not absolutely equal: data types are inconsistent or values are not equal!==

  1. Inconsistent data types
  2. Numeric inequality
  3. Data types are inconsistent and values are not equal

Expressions and Operators

  • Arithmetic Operators
  • String Operators
  • Comparison operator
operatorExplain
==Equals. Returns TRUE if the two operands are equal
===Absolutely equal. Returns TRUE if operands are equal and of the same type
!===Not absolutely equal. Returns TRUE if two numbers are not equal or of inconsistent type
String comparisons are done alphabetically (ascii value codes)
1. Lower case letters are larger than upper case letters
2. Shorter strings are smaller than longer strings
3. Characters at the top are smaller than those at the bottom

Assignment and calculation examples of variables

   //Assignment and calculation examples of variables
                    var int=2017;
			var float=9.21;
			var bool=true;
			var str= "2000";
			document.write(typeof (int) + "and" + typeof (float) + "<br>" );
			document.write(typeof (int) + ":" + int + "<br>");
			document.write(typeof (float) + ":" + float + "<br>");
			document.write(typeof (int - float) + ":" + (int- float) + "<br><br> ");
				
			document.write(typeof (int)+ "and" + typeof (bool) + "<br>");
			document.write(typeof (int)+ ":" +int + "<br>");
			document.write(typeof (bool) + ":" + bool +"<br>");	
			document.write(typeof (int - bool) + ":" + (int-bool) + "<br><br> ");
				
			document.write(typeof (int) + "and" + typeof(str) + "<br>" );
			document.write(typeof (int) + ":" + int + "<br>" );
			document.write(typeof (str) + ":" + str + "<br>" );	
			document.write(typeof (int - str) + ":" +(int-str) +"<br><br> ");
				
			document.write("Data Type Conversion<br>");
			var value="2000.8" ;
			document.write(typeof (value) + ": " +value + "<br>" );
			var int =parseInt(value);
			document.write(typeof (int) + ": " +int + "<br>" );
			var float=parseFloat(value)
			document.write(typeof (float) + ": " +float +  "<br><br> ");

Arithmetic Operators+, -, *, /,%, Examples

	var num1 = 5;
			var num2 = 4;
			document.write("num1 = " + num1 + "  ; num2 = " + num2 + "<br>");
			document.write("num1 + num2 = " + (num1 + num2) + "<br>");
			document.write("num1 - num2 = " + (num1 - num2) + "<br>");
			document.write("num1 * num2 = " + (num1 * num2) + "<br>");
			document.write("num1 / num2 = " + (num1 / num2) + "<br>");
			document.write("num1 % num2 = " + (num1 % num2) + "<br><br>");
							       
			document.write("5+'5' = " + (5 + '5') + "<br>");   //Why did the focus become 55                                                                     
			document.write("5-'5' = " + (5 - '5') + "<br>");   //Why do strings subtract to zero
			document.write("5-'a' = " + (5-'a')+ "<br>"); //NaN Not a Number

Example of comparison operator 1

 //Comparison operator
		var i=5 ; 
		var s=5;
		document.write("i== s yes" +(i==s) + "<br >") //true types can have inconsistent values.
		document.write("i== s yes" +(i===s) + "<br >") //true type and value must be consistent
		document.write("i!== s yes" +(i!==s) + "<br ><br >")//false
  
            var s1="src";
		var s2="proc";
		var s3="procedure";
		document.write("s1 > s2 yes:"+(s1>s2)+ "<br >") //true
		document.write("s2 > s3 yes:"+(s2>s3)+ "<br >") //false
		document.write("a > A yes:"+("a">"A")+ "<br >") //true

Example of string operator splicing

     var str1="Beijing,";
			var str2="Welcome!";
			var str3=str1+str2+"Ha ha ha";
			document.write("str3="+str3+ "<br>");
			var str4="Please pay" + 50 + "Yuan!";
			document.write("str4="+str4+ "<br>");

2. JavaScrip statements and functions

1. if branch structure

  • Simple if statement
  • if...else statement
  • Multiple if statement
  • Nested if statement

if syntax

    if(Conditional expression 1){
        if(Conditional expression 11){
            Statement block 11;
        }else{
         Statement block 12;
        }
    }
    else{
        Statement block 2;
    }

if example

		<script>
           window.onload=function(){
		//Using the prompt function, an input box pops up
		var score=prompt("Please enter your results", "0");
		if(score==100){
                  alert("Full score, you're invited today!")	
		}
	}		
		</script>

if...else example

   <script>
			window.onload=function(){
			var score; //Define variable score to represent score
			score=prompt("Please enter your results"," ") //Use the window object prompt function to pop up an input box
			if(score>=60){  //Determine if score >=60 returns true or false
				alert("Pass the exam!") //Show pass information if score >=60 is true
			}else{
				alert("Fail in the exam!") //Show failures if score <60 is true
			}
		}
		</script>

Multiple if example

<script>
			window.onload=function(){
			var score;
			score=prompt("Please enter your results", " ");
			if(score>=90){
				alert("You did a great job!");
			}else if(score>=80){
				alert("Your results are excellent!");
			}else if(score>=70){
				alert("You've got great results!");
			}else if(score>=60){
				alert("Your results are average!");
			}else{
                           alert("Your results are poor!");
			}	
		}
		</script>

Nested if example

    <script>
				//if statement
				//After onload has finished loading
				//The prompt output statement uses essentially zero for output
				window.onload=function(){
				var score=prompt("Please enter your results" ,"0");
				if (score>100|| score<0) {
						alert("You entered the wrong result!");
					}else{ //[0,100]
					if(score>=85){
						alert("Your performance is excellent");
					}else if(score>=75){
						alert("Your results are excellent!");
					}else if(score>=60){
						alert("Your results are average!");
					}else{
						alert("Your results are poor!");
					}	
				}
			 }
			</script>

2. switch Branch Structure

grammar

 switch(Expression){
        case Constant 1:
                    Statement 1;
        case Constant 2:
                    Statement 2;
                    break;
        ...
        case constant n:
                    Sentence n;
                    break;
        default
                    Sentence n;                                                           
    }

switch example

window.onload=function(){
			var grade; //Define variable grade to represent term number
			grade =prompt ("Please enter a term number (1)-3):" ," ")//Return string type
			//1=="1"
			//1==="1"
			switch (grade){ //===
				case "1": //Conditions are string type
					alert("The courses we are studying this term are HTML JAVA SQL Basics");
					break;
				case "2": //Conditions are string type
					alert("The courses we are studying this term are JS J2SE SQL senior");
					break;
				case "3": //Conditions are string type
					alert("The courses we are studying this term are Struts Spring Hibernat");
					break;		
				default:
					alert("You entered the term incorrectly!");
			}
		}

3. while Loop Structure

while loop statement

while(Conditional expression){
    Circulatory body;
}


while example

window.onload=function(){
				document.write("2008 Year Forbes Top 5 Rich People in the World <br/>");
				var a= b = c = d = 0; //Declare four loop variables
				while(a<=620){
					document.write("█");
					a += 20; //Changing the value of a loop variable
				}
				document.write("     Warren Buffett: 620 $100 million<br/>");
				while (b<=600){
					document.write("█");
					b += 20;
				} 
				document.write("     Carlos Slim Helu: 600 $100 million<br/>");
				while (c<=580){
					document.write("█");
					c += 20;
				}
				document.write("     William  Gates: 580 $100 million<br/>");
				while (d<=450){
					document.write("█");
					d += 20;
				}
				document.write("     Lakshmi Mittal: 450 $100 million<br/>");
			}

4. do...while loop

do...while loop syntax

   do{
    Circulatory body;
    }while (Conditional expression);


principle

  1. Execution followed by loop condition judgment
  2. If the loop succeeds, go back and forth. If the judgement is unsuccessful, skip over
  3. It will execute at least once

do...while example

<script>
		window.onload=function(){
			document.write("<p> Please enter a few letters to see the effect:,</p>");
			do{
				var character=prompt("Please enter a letter, enter N Or n" , "B");
				document.write("<span style=font-size:36px;>"+character+"</span>");
				}while(character !="n" && character !="N")
			}
		</script>

5. for Loop Structure

for loop syntax

  for(initial value; condition; increment){           //Increment = Step value
    Circulatory body;
    }    


for loop example 99 multiplication table

	<script>
			for(var row=1; row<=9; row++){  //That's ok
				for(var col=1; col<=row; col++){  //column
					document.write(col+ "*" +row+ "=" +row*col+ "&nbsp;&nbsp;");
				}
				document.write("<br>");  //Line break at end of each line
			}
		</script>

break statement: jump out of executing loop structure

	<script type="text/javascript">
			//break loop
					window.onload=function(){
						var counter=1 ; //Set loop variable and give initial value 1
						var sum=0;		//Store and variable to initial value 0
						while(true){ //Mainly here is the dead loop
						
				//This is the use of continue
						// if(counter %2 !=0){
						// 	counter++; //Change the cycle condition to give the loop an opportunity to end
						// 	continue;
						// }
						sum +=counter ;  //Cycle things to do, add up
						if(counter==10){ //Use the if statement to determine how to add to 10 and use break
							break;
						}
						counter++; //Changing the cycle conditions gives you the opportunity to end the cycle
					}
					document.write("The sum of the first 10 even numbers is: "+sum); //Output cumulative results
					}
			</script>

continue statement: Ignore the following statement and execute from the next loop

<script>
		//continue cycle
				window.onload=function(){
					var output=" "; //String holding output results
					var temp=0;		//Store and variable to initial value 0
					while(temp<=100){ 
					temp++;
					if(temp%2==1){   //Odd number if true
						continue;  //If it's odd, the code that follows skips, starting with the next loop
					}
					output=output+temp+"<br>"; //With spaces, the output will not be joined together
				}
				document.write(output); //Output cumulative results
				}
		</script>

How do I sum the first 10 even numbers by using break and continue statements together?

window.onload=function(){
			var counter=1 ; //Set loop variable and give initial value 1
			var sum=0;		//Store and variable to initial value 0
			while(true){ //Mainly here is the dead loop
			if(counter %2 !=0){
				counter++; //Changing the cycle conditions gives you the opportunity to end the cycle
				continue;
			}
			sum +=counter ;  //Cycle things to do, add up
			if(counter==10){ //Use the if statement to determine how to add to 10 and use break
				break;
			}
			counter++; //Changing the cycle conditions gives you the opportunity to end the cycle
			
		}
		document.write("The sum of the first 10 even numbers is: "+sum); //Output cumulative results
		}

6. Functions

Meaning: A method like Java or C# is a block of statements that perform a specific task. When a task needs to be repeated, related statements can be organized into functions.

Examples of functions

<title></title>
		<script>
			function show()  //Define a function with no parameters and no return values
			{
				alert("I'm in a good mood today!")
			}	
		</script>
	</head>
	<body>
		<p><input type="button" value="display" onclick="show()"/></p>
	</body>

Definition and invocation of functions
Definition of function: syntax

    function Function name( [parameter list] ){
        Program Statement
        [return Return value;]
    }

Calls to functions

  • Use function calls with events on form elements
  • The call format is: Event name = "Function name"

Matters needing attention

Matters needing attention:
Function names are case sensitive and cannot be the same, let alone use Javascript keywords.
You cannot specify the data type of the return value before the function: keyword
In a function definition, [] is optional, that is, a custom function can have parameters or no parameters. If there are parameters, the parameters can be variables, constants, or expressions. A custom function can have return values or none, or if the retur statement is omitted, the function returns undefined.
The parameter list of a function does not specify the data type of the parameter like Java, only the parameter quantity name is written.
If there are multiple parameters in the parameter list, they need to be separated by','.
Functions must be placed between < script> </script tags.
Definitions of functions are best placed in sections of web pages or stand-alone*.JS file.
Defining a function does not execute the code that composes it; it executes only when the function is called

Functions without parameters

Is it possible to define a function without giving a list of parameters,What about giving arguments when calling a function??
Tolerable,Use inside a function arguments Array object to access all arguments passed by the program to a function when it is called

Examples of functions without parameters

<title></title>
		<script>
			function sumbetween()  //This function returns the sum of all integers from num1 to num2
			{
				var tocal=0,temp;
				for(temp=arguments[0] ; temp<=arguments[1] ; temp++){
					tocal = tocal+temp;
				}
				return tocal; //Function return value 
			}			
		</script>
	</head>
	<body>
		<script>
			var sum=sumbetween(1,100); //Call show() function
			document.write("1 Sum of all integers to 100 is"+sum);
		</script>
	</body>

Functions with parameters

Calculates the sum of integers for any given interval

  1. Define a function with parameters, using two parameters to represent the left and right ends of an interval
  2. Loop through the numbers in the accumulated interval in a function to add up and return
  3. Enter an interval value in the code calling the function and use the variable to receive the return value
  4. Using data, displaying and

Examples of functions with parameters

<title></title>
		<script>
			function show(num1,num2)  //This function returns the sum of all integers from num1 to num2
			{
				var tocal=0,temp;
				for(temp=num1 ; temp<=num2 ; temp++){
					tocal +=temp;
				}
				return tocal; //Function return value 
			}			
		</script>
	</head>
	<body>
		<script>
			var sum=show(1,100); //Call show() function
			document.write("1 Sum of all integers to 100 is"+sum);
		</script>
	</body>

7. Global and local variables

global variable

  • Variables declared directly in the < script></ script> tag are independent of all functions.
  • Scope is all statements after the variable is declared, including those subsequently defined in the function

local variable

  • A variable declared in a function can only be used by program code in that function and after the variable is declared
  • Variables in the parameter list of a function also belong to local variables of the function.
  • Local variables must belong to a function and are therefore inaccessible to subsequent functions and script code
  • If a variable with the same name as this local variable is declared in subsequent other functions and script code, there is no relationship between the two variables.

Example

<title>Example</title>
		<script>
			var number=100,
			    sum=100;  //Declare two global variables
			function changeValue(){
			var number=10;//Declare the number of local variables with the same name as the global variable
			document.write("number =" + number + "<br>"); //Output local variable number
		    document.write("sum = " + sum +"<br>"); //Output global variable sum
			 }
		</script>
		<script>
			changeValue(); //Call function
			document.write("<h2> number= " + number+ "</h2>");//Output global variable number	
		</script>

8. Built-in Functions

Parselnt (String) function

  • Converts a string to an integer number
  • For example, parselnt("866") converts the string "86.6" to an integer value of 86

ParseFloat (String) function

  • Converts a string to a floating-point number
  • For example, parsefloat("34.45") converts string "34.45" to floating point value 34.45

isNaN() function

  • Determines whether a variable or a string is non-numeric. Returns true or false otherwise
  • For example, isNaN("ab") will return true, and isNaN("12") will return False.

eval() function

  • Executes a string as a Javascript expression and returns the result of execution.

isFinite() function

  • Check if the number is infinite, return tue, otherwise false
//Test 1. Parselnt (String) function
			var num=parseInt("86.6");  //Rounding does not round 86
			alert(num);
   //Test 2. ParseFloat (String) function
			var num=parseFloat("86.6");  //Conversion to decimal does not round 86.6
			var num=parseFloat("86.6a");  //86.6 It omits transitions that can be converted but cannot be converted
			alert(num);
   //Test 2, isNaN() function
			var num=5-"5";  //0
			var num1=5-"a";	//NaN +, string stitching
			var num2=isNaN("86.6a"); //Truis Not a Nomber means it is a non-numeric value
			alert(num);
			alert(num1);
			alert(num2);
   //Test 3, eval() function
			 var num=eval("3+8*3");  //27
			 var num=eval("(3+8)*3");  //33
			alert(num);

**Simple Computer Case**

<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#tb{
				border: 1px solid gray;
				width: 500px;
				height: 300px;
				margin: auto;
			}
			
			.text{
				width: 200px;
				height: 30px;
				border: 1px solid gray;
			}
			.btn{
				width: 50px;
				height: 30px;
				border: 0;
				font-weight: bold;
			}
		</style>
		
		<script>
			function calc(op){
			var a=document.getElementById("one").value;
			var b=document.getElementById("two").value;
			var resuit;
			result=eval(a+op+b);
			document.getElementById("result").value=result;
			}
		
		</script>
		
	</head>
	<body>
		<form action="#" method="get" >
		<table id="tb" >
			<tr>
				<td align="right">Please enter the first number:</td>
				<td colspan="4"><input class="text" type="text" id="one"/></td>
			</tr>
			
			<tr>
				<td align="right">Please enter the second number:</td>
				<td colspan="4"><input class="text" type="text" id="two"/></td>
			</tr>
			
			<tr>
				<td align="right">operator:</td>
				<td><input type="button" value="+" class="btn"  onclick="calc('+')"/></td>
				<td><input type="button" value="-" class="btn"  onclick="calc('-')"/></td>
				<td><input type="button" value="*" class="btn"  onclick="calc('*')"/></td>
				<td><input type="button" value="/" class="btn"  onclick="calc('/')"/></td>
			</tr>
			
			<tr>
				<td align="right">The result of the operation is:</td>
				<td colspan="4"><input class="text" type="text" id="result"/></td>
				</tr>
		</table>	
		</form>
		
	</body>
</html>

3. JavaScrip Objects (1)

1. Attributes, methods, events

attribute

  • Attributes refer to the values contained in an object, manipulated in the form of "object name. attribute name", such as document.Myfron.first.Value

Method

  • In the code, the object's method is called with the object name.method name ().
  • alter() =Windows. alter(")

Event

  • Respond to user actions, complete interactions, such as Onclick, OnkeyDown
  • They can generally be divided into mouse events, keyboard events, and other events

2. Objects in JavaScript

Javascript Functions are endowed with many features, one of the most important of which is the use of functions as first-type objects.
That means javascript Medium functions can have attributes, methods, and properties owned by all objects. Most importantly, they can also be called directly

custom object

  • New objects defined by developers according to their needs.

Javascript built-in objects

  • Javascript predefines some common functions as objects that users can use directly, which are built-in objects.
  • Such as character application object, mathematical object, date object, array object, regular expression object, etc.

Browser Built-in Objects

  • Browser objects are the series of available objects that browse Javascript based on the current configuration of the system and the pages loaded
  • Such as Window object, Document object, History object, etc.

3. How to create custom objects

Two ways

  1. Create objects using Object keywords
  2. Creating objects using the function keyword

Example of creating objects using Object keywords

	<script>
    			var car=new Object();
				//assignment
				car.name="Audi A9";
				car.color="black";
				car.run=function(){
					return this.name+"Maximum speed 280 hours km"
				};
			/*  //You can also define before calling
				car.run = runFun();
				function runFun(){
				document.write("<BR>Maximum speed 280km ";
				};
						*/
			//call
			document.write("Model," +car.name +"<br>");
			document.write("colour," +car.color +"<br>");
			document.write("Explain," +car.run() +"<br>");
		</script>

Example of creating objects using function keywords

<script>
			function Car(name,color){
				this.Name=name;
				this.Color=color;
				this.Run=function(){
					return this.Name+"Maximum speed 280 hours km"
				};
			}
			//Car.prototype.Stp=function(){}
			var car=new Car("Audi A9", "black");
			//car.Stop();
			document.write("Model," +car.Name +"<br>");
			document.write("colour," +car.Color +"<br>");
			document.write("Explain," +car.Run() +"<br>");
		</script>

Be careful

Object Keyword uses more because it extends
 Extension Code Direct //car.
and function Because its content is used in methods this . Problem prone
 Extension Code//Car.prototype.Stp=function(){} 
Many frames function More 

4. Strings

  • Used to store a series of characters
  • Use single or double quotation marks to include
var name="Xie Chan Software";
mvarhttp='www.xiecan.cc';
  • You can use an index to access any character in a string
var char=http [5];

Poor compatibility, only compatible with high-version browsers, not E6-8

  • You can use quotation marks in strings
var full="Xie Chan Software 'Www. Xietan.cc'"
full="Xie Chan Software\"ww. Xietan.cc' "   //   \Backslash is an escape character

Be careful

stay js There is no difference between a character and a string in

5. String Method

Method (parameter list) propertiesExplain
lengthReturn string length
charAt(num)Returns the character at the index specified by the parameter num (in js this is what the java cursor can look for)
charCodeAt(num)Returns the Unicode value of the character at the specified index for the parameter num
indexOf(string [, num])Returns the position of the first occurrence of the parameter string in a string
lastIndexOf(string [,num] )Returns the last occurrence of the string argument string
substring(index1 [,index2 ])Returns the string between index1 and index2 in a string
substr(index1 [,num] )Returns num characters after index1 in a string
toUpperCase()Returns string uppercase
toLowerCase()Returns string lowercase
split(reg, num)Split a string into an array of strings based on the regular expression or character (string) passed in by the parameter
replace(reg, string)Replace the string with a new string based on the regular expression or character (string) passed in by the parameter
search(string)Returns where the parameter string appears
<script>
			var name="Xie Chan Software";
			var http='www.xiecan.cc';
			//output
			document.write(name +http +"<br>");  //Scan Software www.xiecan.cc
			//You can use an index to access any character in a string
			document.write(name[0]+ "<br>");  //thank
			//You can use quotation marks in strings			
			var full="Xie Chan Software'ww. xietan.cc";
			document.write(full +"<br>");//Scan Software'www.xiecan.cc
			full= "Xie Chan Software\"www.xiecan.cc\" ";
			//fu11='Xie Can Software'www.xiecan.cc'
			document. write(full+"<br>");//Xie Chan Software "www.xiecan.cc"
			//Return string length
			document.write(full.length +"<br>");//20
			//Returns the character at the index specified by the parameter num (in js this is what the java cursor can look for)
			document.write(full.charAt(13)+"<br>"); //a
			//Returns the Unicode value of the character at the specified index for the parameter num
			document.write(full.charCodeAt(13)+"<br>"); //97
			//Returns the position of the first occurrence of the parameter string in a string
			document.write(full.indexOf('w')+"<br>"); //5
			//Returns the last occurrence of the string argument string
			document.write(full.lastIndexOf('w')+"<br>"); //7
			//Returns the string between index1 and index2 in a string
			document.write(full.substring(4)+"<br>"); //"www.xiecan.cc"
			document.write(full.substring(4,8)+"<br>");  //"www.
			//Returns num characters after index1 in a string
			document.write(full.substr(4)+"<br>"); //"www.xiecan.cc"
			document.write(full.substr(4, 8)+"<br>");//www.xie
			//Returns string uppercase
			document.write(full.toUpperCase()+"<br>");//Xie Chan Software "WWW.XIECAN.CC"
			//Returns string lowercase
			document.write(full.toLowerCase()+"<br>");//Xie Chan Software "www.xiecan.cc"
			//Split a string into an array of strings based on the regular expression or character (string) passed in by the parameter
			document.write(full.split(' " ')+"<br>"); //Scan Software, www.xiecan.cc,
			//Replace the string with a new string based on the regular expression or character (string) passed in by the parameter
			document.write(full.replace('w','w')+"<br>"); //Xie Chan Software "www.xiecan.cc"
			//Returns where the parameter string appears
			document.write(full.search('www')+"<br>"); //5
		</script>

String - Examples of validating mailboxes

<title></title>
		  <style type="text/css">
		            body
		            {
		                text-align:center;
		            }
		            #text1
		            {
		                font-weight:bold;
		            }
		            #Button1
		            {
		                color:Blue;
		            }
		        </style>
		 <script type="text/javascript">
		            window.onload = function () {
		                var btn = document.getElementById("Button1");
		                btn.onclick = function () {
		                    var txt = document.getElementById("Text1").value;
		                    if (txt.indexOf("@") == -1) {
		                        alert("Mailbox must contain@!");
		                    }
		                    else if (txt.indexOf(".") == -1) {
		                        alert("Mailbox must contain.!");
		                    }
		                    else if (txt.indexOf("@") > txt.indexOf(".")) {
		                        alert("@Must be in.Front!");
		                    }
		                    else {
		                        alert(txt);
		                    }
		                }
		            }
		        </script> 
	</head>
	<body>

		 <input id="Text1" type="text" value="xiecansoft@qq.com"/>
		  <input id="Button1" type="button" value="Check Mailbox" />	
	</body>

String - Example of validating a password

<title></title>
		 <style type="text/css">
		            body
		            {
		                text-align:center;
		            }
		            #text1
		            {
		                font-weight:bold;
		            }
		            #Button1
		            {
		                color:Blue;
		            }
		        </style>
				
				<script type="text/javascript">
				    window.onload = function () {
				        var btn = document.getElementById("Button1");
				        btn.onclick = function () {
				            var txt = document.getElementById("Pwd1").value;
				            for (var i = 0; i < txt.length; i++) {
				                var ch = txt.charAt(i);
				                if ((ch >= '0' && ch <= '9')//Verify Number
				                || (ch >= 'a' && ch <= 'z')//Verify lowercase
				                || (ch >= 'A' && ch <= 'Z')//Verify capitalization
				                || (ch == '_')) {//Verify underline
				                    continue;
				                }
				                else {
				                    alert("The password contains illegal characters!");
				                    break;
				                }
				            }
				        }
				    }
				</script>
	</head>
	<body>
		        <input id="Pwd1" type="password" value="xiecansoft@qq.com"/>
		        <input id="Button1" type="button" value="Check password" />	
	</body>

6. Mathematical Objects

  • Mathematical objects provide basic mathematical functions and constants
  • Mathematical objects do not require the new operator
attributeExplain
LN10Returns the natural logarithm of 10
LN2Returns the natural logarithm of 2
LOG10EReturns the base 10 logarithm of e
LOG2EReturns the base 2 logarithm of e
PIReturn the circumference, about 3.141592653...
SQRT1 2Returns the square root of 0.5
SQRT2Returns the square root of 2
EReturns the natural constant E, about 2.718

function

MethodExplain
abs(x)Returns the absolute value of x
cos(x)/acos(x)The cosine inverse cosine value returned.
sin(x)/asin(x)Returns the sine-arc sine of x.
atan(x)Returns the inverse tangent of x.
ceil(x)/floor(x)Round logarithms up/down.
exp(x)Returns the exponent of e.
log(x)The natural logarithm of the return number (bottom e)
max(x, y)/min(x,y)Returns the minimum and maximum values in x and y
pow(K,y)Returns the y-power of x.
random()Returns a random number between 0 and 1. [0,1]
round(x)Round a number to the nearest integer
sqrt(x)Returns the square root of a number.

Be careful

There are three values associated with values: 
ceil(x)/floor(x)  Logarithmic Ongoing/Round down.41.5 Up 42  
round(x) Round a number to the nearest integer
random() Return 0-1 Random number between.[0,1)  The value he returns is a decimal. It contains zero, does not contain one and always is zero.12  0.1 several
 <script type="text/javascript">
                 //Returns the absolute value of x
	            document.write(Math.abs(-20) + "<br>");//20
                //Returns the sine-arc sine of x. The value is very close to 0
	            document.write(Math.sin(Math.PI) + "<br>"); //1.2246467991473532e-16
	            document.write(Math.asin(1) + "<br>"); //1.5707963267948966
	            document.write(Math.cos(Math.PI) + "<br>"); //-1
	            document.write(Math.acos(1) + "<br>");//0
		   //PI / 4 is pi quarter should be 1 but he is close to 1 because of error
	            document.write(Math.tan(Math.PI / 4) + "<br>"); //0.9999999999999999
	            document.write(Math.atan(1) + "<br>"); //0.7853981633974483
		    //Round logarithms up/down.
		    //Up to Up
	            document.write(Math.ceil(Math.PI) + "<br>"); //4
		    //Full Down
	            document.write(Math.floor(Math.PI) + "<br>"); //3
		    //round
	            document.write(Math.round(Math.E) + "<br>"); //3
		    //Comparison of maximum and minimum PI with 3.2
	            document.write(Math.max(Math.PI, 3.2) + "<br>");//3.2
	            document.write(Math.min(Math.PI, 3.2) + "<br>"); //3.141592653589793
		    //pow is taking his power and the power is the square of PI
	            document.write(Math.pow(Math.PI, 2) + "<br>"); //9.869604401089358
		    //Take square root
	            document.write(Math.sqrt(Math.E) + "<br>"); //1.6487212707001282
	            document.write(Math.random() + "<br>");//Random number between 0-1 [0,1)
	        </script>

7. Date object

  • The Date object contains information about the date and time
  • No properties, only methods to get or set the date and time
MethodExplain
Date()Returns the date and time of the day.
getDate()Returns a day of the month (1-31) from the Date object.
getDay()Return a day of the week from the Date object (0-6)
getMonth()Return month from Date object (0~11)
getFullYear()Returns the year from the Date object in four digits.
getHours()Hours returned for Date objects (0~23)
getMinutes()Returns the minutes of the Date object (0~59)
getSeconds()Number of seconds (0~59) to return a Date object
getMiliseconds()Returns the milliseconds (0~999) of the Date object
geTlime()Returns the milliseconds since January 1, 1970

Be careful

Don't forget to put a bracket when you use it
 Be sure to add 1 when getting months  getMonth() from Date Object returns month(0~11)  only+1 To get the current month
getDay() Get a value of 1 for Monday and 0 for Sunday
getFullYear() and getYear()Differences between getFullYear()Get four-digit 2020  getYear()Get the last two 20

Get an example of the time at that time

<script type="text/javascript">
				window.onload = function() {
					var time = new Date();
					document.write(time.getFullYear() + "year<br>");
					document.write(time.getMonth() + 1 + "month<br>");
					document.write(time.getDate() + "day<br>");
					document.write("week" + time.getDay() + "<br>");
					document.write(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds() + "<br>");
				}
			</script>

8. Supplement

1. The Role of new Keyword

The new keyword does the following:

  • Create an empty simple JavaScript object (that is, {});
  • Link the object (that is, set its constructor) to another object;
  • Make the newly created object in step 1 the context of this;
  • If the function does not return an object, it returns this.

object JavaScript objects are an unordered collection data type consisting of several key-value pairs.

function getAge() {
    var y = new Date().getFullYear();
    return y - this.birth;
    
}

var xiaoming = {
    name: 'Xiao Ming',
    birth: 1990,
    school: 'No.1 Middle School',
    height: 1.70,
    weight: 65,
    age: getAge,
    score: null    //The last key pair does not need to be added at the end, and if it is added, some browsers, such as lower versions of IE, will fail.
};

xiaoming.name; // 'Xiao Ming'
xiaoming.birth; // 1990
xiaoming['birth'];   //1990

console.log(xiaoming.job); // Accessing a non-existent property does not error, but returns undefined:


xiaoming.age(); //Normal call returned 25, 
getAge(); // NaN is the pit of error this if called alone 


2. Strings

//Length character variable length
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";       
document.getElementById("demo").innerHTML = txt.length;  //The length property returns the length of the string: 26
/*
Example//China is the home of porcelain, so China has the same name as China.
HTML Medium <, >, &etc. have special meaning (<, >, for link labels, &for escape) and cannot be used directly. These symbols are not displayed in the pages we eventually see. What if we want them to be displayed on the pages?
\b	Backspace
\f	Page Change
\n	Line Break
\r	Enter
\t	Horizontal Jump Grid (Ctrl-I)
\'	Single quotation mark
\"	Double Quotes
\\	Backslash
*/
//Escape sequence \"Insert double quotation marks in the string.
var x = "China is the home of porcelain, so china and\"China(China)\"Same name.";  //China is the home of porcelain, so China has the same name as China.
document.getElementById("demo").innerHTML = x; 
//The escape sequence\inserts a backslash into the string.
var x = "character \\ It is called backslash.";
document.getElementById("demo").innerHTML = x; //The character \ is called a backslash.
//The indexOf() method returns the position where the specified text first appears: Return-1 if no text is found.
var str = "Gently I went, just as gently I came;"
var pos = str.indexOf("gently");
document.getElementById("demo").innerHTML = pos;  //0

//Accept the second parameter as the starting index location from where to find
var str = "Gently I went, just as gently I came;"
var pos = str.indexOf("gently",5);
document.getElementById("demo").innerHTML = pos;  //10
//Last occurrence (look back and forward)
//lastIndexOf() returns the last occurrence of the specified text, or -1 if no text is found.
//Look forward from behind the array for the first occurrence of the target number and return its normal index value
var str = "Gently I went, just as gently I came;";
var pos = str.lastIndexOf("gently");
document.getElementById("demo").innerHTML = pos;   \\Output 10

//The lastIndexOf() method accepts the second parameter as the starting location for the search:
//
//Keep in mind that the lastIndexOf() method searches backwards, so position 20 means the search starts at position 20 and starts at the beginning.
var str = "Gently I'm gone,Just as I came lightly;";
var pos = str.lastIndexOf("gently",20);
document.getElementById("demo").innerHTML = pos;    //Return 10
//Find one character and return index subscript at another character position
//The search() method returns the first occurrence of the specified text in the string:
var str = "The full name of China is the People's Republic of China.";
var pos = str.search("China");
document.getElementById("demo").innerHTML = pos;  //Return 17
//The two methods, indexOf() and search(), are equal. 
//     The two methods are not equal. The difference is:
//         The search() // method cannot set the second start position parameter. However, regularity is supported.
//         The indexOf() method cannot set a more powerful search value (regular expression), but it can set the starting position

3. Extract partial strings

There are three ways to extract partial strings:

  1. slice(start, end)//The difference between how many to how many and below can be-indexed
  2. substring(start, end)//The difference between how many to how many and above cannot be negative indexed
  3. substr(start, length)//Take several last parameters from a few and take a few
//slice() extracts a part of a string and returns the extracted part in a new string.
//This method sets two parameters: the start index (start position) and the end index (end position).
//This example clips the fragment from position 7 to 13 in the string:
var str = "Apple, Banana, Mango";
var res = str.slice(7,13);
document.getElementById("demo").innerHTML = res;    //Banana

//If the second parameter is omitted, the method clips the rest of the string:
var res = str.slice(7);
document.getElementById("demo").innerHTML = res;  //Banana, Mango
//substring() method
//substring() is similar to slice().
//The difference is that substring() cannot accept negative indexes.
//substring() extracts a part of a string and returns the extracted part in a new string.
var str = "Apple, Banana, Mango";
var res = str.substring(7,13);
document.getElementById("demo").innerHTML = res; //Banana
//If the second parameter is omitted, the substring() clips the rest of the string.
//substr() is similar to slice().
//The difference is that the second parameter specifies the length of the extracted part.
var str = "Apple, Banana, Mango";
var res = str.substr(7,6);   //Banana
//If the second parameter is omitted, the substr() clips the rest of the string.
var res = str.substr(7);   //Banana, Mango

4. Replace string contents

//The replace() method replaces the value specified in the string with another value:
//The replace() method does not change the string that calls it. It returns a new string.
//By default, replace() replaces only the first match:
//replace() is case sensitive.
str = "Apple, Banana";
var n = str.replace("Banana", "Mango");   //Apple, Mango

5. Convert to uppercase and lowercase

//Convert the string to uppercase by toUpperCase():
var text1 = "Hello World!";      
var text2 = text1.toUpperCase();  // HELLO WORLD!

//Convert the string to lowercase by toLowerCase():
var text1 = "Hello World!";       // Character string
var text2 = text1.toLowerCase();  // hello world!

6. Remove Spaces

//String.trim()
//The trim() method removes whitespace at both ends of the string:
//Note: Internet Explorer 8 or lower does not support the trim() method.
  var str = "     Hello World!     ";
  str.trim();   //Hello World!

7. Extracting String Characters

//charAt() method
//The charAt() method returns the string in which the subscript (position) is specified:
var str = "HELLO WORLD";
str.charAt(0);            // Return H
//charCodeAt() method
//The charCodeAt() method returns the character unicode encoding of the specified index in the string:
var str = "HELLO WORLD";
str.charCodeAt(0);         // Return 72'

8. Convert Strings to Arrays

//Strings can be converted to arrays by splitting ():
var str = "H'e'l'l'o";
var arr = str.split("'");                               
var text = "";
var i;
for (i = 0; i < arr.length; i++) {
  text += arr[i] + "<br>"
}
document.getElementById("demo").innerHTML = text; 
//output
H
e
l
l
o

9. Digital Objects

//Math.round()
//The return value of Math.round(x) is x rounded to the nearest integer:
Math.round(6.8);    // Return 7
Math.round(2.3);    // Return 2
//Math.abs()
//Math.abs(x) returns the absolute (positive) value of x:
Math.abs(-4.7);     // Return 4.7

//Math.ceil()
//The return value of Math.ceil(x) is the nearest integer rounded to x:
Math.ceil(6.4);     // Return 7
//Math.floor()
//The return value of Math.floor(x) is the nearest integer rounded down by x:
Math.floor(2.7);    /
//Math.min() and Math.max()
//Math.min() and Math.max() can be used to find the lowest or highest values in the parameter list:
Math.min(0, 450, 35, 10, -8, -300, -78);  // Return-300
Math.max(0, 450, 35, 10, -8, -300, -78);  // Return 450
//Math.random() returns a random value between 0 and 1:
Math.random()  //0.08851988681973033

Date object

document.write(Date()) Wed Apr 08 2020 14:06:07 GMT+0800 (China Standard Time)

Keywords: Javascript ASP.NET html

Added by TMX on Tue, 28 Sep 2021 19:40:07 +0300