July 12, 2021 - preliminary review of JavaScript

javaScript Basics

1, Learn what JavaScript is

JavaScript (JS for short) is a lightweight, interpretive or just in time programming language with function priority. Although it is famous as a scripting language for developing Web pages, it is also used in many non browser environments. JavaScript is a dynamic scripting language based on prototype programming and multi paradigm, and supports object-oriented, imperative, declarative and functional programming paradigms.
JavaScript was invented by Brendan Eich in 1995 and became an ECMA standard in 1997.
ECMA-262 is its official name. ECMAScript 6 (released in 2015) is the latest version of JavaScript.

2, Quick start

1. Introducing JavaScript

1. Internal label
- js in HTML, JavaScript code must be between tags.

<script>
	alert("Pop up a pop-up message");
</script>
/*Note: old JavaScript may use the type attribute: < script type = "text / JavaScript" >.

Note: the type attribute is not required. JavaScript is the default scripting language in HTML.*/

You can place any number of scripts in an HTML document.

Scripts can be placed in or part of an HTML page, or both.

2. External label
abc.jsp

	function myFunction() {
    document.getElementById("demo").innerHTML = "This is·A revised paragraph.";
}

test.html

<script src="abc.js"></script>

2. Basic grammar

JavaScript syntax is a set of rules that define the language structure of JavaScript.

<!--Strict case requirements-->
<script>
// Define variable type, variable name = variable value
/* In programming languages, variables are used to store data values.
JavaScript Use the var keyword to declare variables*/

var num = 1 ; 
var h1 = 2 ;
var score = 59;
// 2. Condition control
if(2>1){
	if(3>1){
	alert("true");
	}	
}
if( score>60 && score<70 ){
	alert("pass");
}else if(score>70){
	alert("excellent");
}

//console.log(score) prints variables on the browser console
</script>

All JavaScript variables must be identified by a unique name. These unique names are called identifiers. Identifiers can be short names (such as x and y) or more descriptive names (age, sum, totalVolume). The general rules for constructing variable names (unique identifiers) are:
The name can contain letters, numbers, underscores, and dollar symbols
The name must begin with a letter
Names can also be $and_ start
Names are case sensitive (Y and y are different variables)
Reserved words (such as JavaScript keywords) cannot be used as variable names

data type

Values, text, images, audio, video....

number
js does not distinguish between decimal and integer Number

	123 //integer
	453.1//Floating point number
	1.26e3//Scientific counting method
	-99//negative
	NaN  //Not a number is not a number
	Infinity //Represents infinity

character string
'abc'
"abc"

Boolean value
true false
Logical operation

&& Both are true and the result is true
|| One is true and the result is true
!True is false, false is true

Comparison operator

=
== Equal to (if the type is different and the value is the same, it will also be judged as true)
=== Absolutely equal to (the same type, the same value, and the result is true)

Here is a defect of js. Insist not to use = = comparison
Notice:

  • NaN === NaN, which is not equal to all values, including itself
  • Whether the number is NaN can only be determined by isNaN (NaN)

Floating point number problem: avoid floating point number operation as far as possible, and there are accuracy problems

	console.log(1/3)===(1-2/3)                  false
	console.log(Math.abs(1/3-(1-2/3)<.0.00000001)    true

null and undefined

  • Null null
  • undefined not defined

=Array=
A series of the same array types

var arr = [1,2,4,"asd",null,ture]
new Array(1,2,4,"asd",null,ture)

=Object=
Objects are braces and arrays are parentheses
Each attribute is separated by an object, and the last one is not comma

<script>
	var Person{
		name:"name",
		age:3,
		tags:['js',2.4,23]
		
	}
</script>

Get the value of the object

Person.name

Person.age

=Strict inspection mode=
use strict: strictly check the mode to prevent problems caused by the randomness of JavaScript

<script>
	'use strict';//The premise idea setting supports ES6 syntax and must be written in the first line of script
	var i = 1;
	a = 1; //The a variable here is a global variable. If it is not used, it is a random variable, and you will be prompted to modify it
</script>

=String=

  1. escape sequence
\'
\n
\t
\x41 Ascll character
\u4e2d  \u#### Unicode character

Sequence "insert double quotes in string:

var x = "China is the hometown of porcelain, so china And\"China(China)\"Same name."
  1. Multiline string writing
//tab above and esc below
var msg=`hello
world
1
2
3
`
  1. Template string
let name ="name";
let age=3;
let msg ="hello ${name}";
  1. String length
    str.length

  2. Immutability of string
    The string in js will not change due to the operation of the console

  3. Case conversion

<script>
	student.toUpperCase();
	student.toLowerCase();
</script>
  1. student.indexOf("t")
  2. substring
studnet.substring(1) //Intercept from the first string to the last string
student.substring(1,3)//[1,3)
  1. Retrieves a string from a string
    The search() method searches for a string of a specific value and returns the matching location:
var str = "The full name of China is the People's Republic of China.";
var pos = str.search("locate"); 
  1. Extract partial string
    There are three ways to extract partial strings:
    slice(start, end)
    substring(start, end)
    substr(start, length)

substring() is similar to slice(). The difference is that substring() cannot accept negative indexes, and negative positions are not applicable to Internet Explorer 8 and earlier versions. If the second parameter is omitted, the substring() will reduce the rest of the string. The difference between the substr() method and slice is that the second parameter of substr() specifies not the end position, but the specified extraction length

  1. Using the replace() method does not change the string that calls it. It returns a new string
str = "Please visit Microsoft!";
var n = str.replace("MICROSOFT", "W3School");

By default, replace() is case sensitive. Therefore, MICROSOFT is not matched
To perform a case insensitive substitution, use the regular expression / i (case insensitive):

str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3School");

Note that regular expressions here are not quoted
To replace all matches, use the g flag of the regular expression (for global search)

str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3School");
  1. concat() connects two or more strings:
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);
  1. The trim() method deletes the whitespace at both ends of the string:
var str = "       Hello World!        ";
alert(str.trim());

IE 8 or earlier does not support trim, so you need to use replace to replace blank space

var str =

3.2 array
Array can contain any data type

var arr =[1,2,3,4,5]
arr[0]
1
  1. length
arr.length()

Note: if you add an assignment to arr.length, the size of the array will change. If the assignment is too small, the elements will be lost

  1. indexOf, which obtains the subscript index through the element
var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China", 18);

The lastIndexOf() method retrieves backward (from end to end), which means that if the second parameter is 50, the retrieval starts from position 50 to the beginning of the string.

var str = "The full name of China is the People's Republic of China.";
var pos = str.lastIndexOf("China", 50);
  1. slice() intercepts part of the Array and returns a new Array. Similar to substring in String
  2. push(), pop() tail
push ;Press in the tail
pop:Eject tail
  1. Unshift() head
unshift Press in the head
shift Pop up an element in the header
  1. sort
arrs.sort()
  1. Element flip reverse()
  2. Splice string concat()
    Note that concat does not modify the array, but returns a new array
  3. Connector join
arr=[a,b,c]
arr.join("-")
a-b-c

Multidimensional array

arr=[[1,2,3],[4,5,6,],[7,8,9]]

==Code analysis==

<!DOCTYPE html>
<html>
<head>
<script>

function mytest(){
	var studentList = ['1','2','4'];
    var i ;
    for (i of studentList) {
     document.getElementById("xb").innerHTML = i ;
      alert(i);
      debugger;
	}
		
}
function myFunction() {
    document.getElementById("demo").innerHTML = "Modify the code snippet test.";
}

function reduce(){
	
    var i = 1/3 ;
    var x = (1 - 2/3);
    let j = "3.3";
    var f = 3.3;
    a = (j==f);
    t = (j===f);
    j = f ;
    alert(a);
  
	document.getElementById("xb").innerHTML = t ; // Judge the type result before strong turn
    document.getElementById("lz").innerHTML = j; // Judge the value of j after forced rotation
    document.write(typeof j);     // Clear the type of HTML print j
}

</script>
	
</head>
<body>
	<button type="button" onclick = "reduce()"> click </button>
    
    <h id = "xb">Display results</h>
    <p id = "lz">1111</p>
</body>

In javaScript, there is no value variable whose value is undefined, and typeof returns undefined
The typeof operator returns one of the following primitive types:

  • string
  • number
  • boolean
  • undefined

The typeof operator returns an array as "object" because in JavaScript, an array is an object.

Through JavaScript, you can access the complete array by referencing the array name:

	var cars = []

All keys in JavaScript are strings, and values are arbitrary objects

Detailed explanation of object types

<script>
var Object name = {
	Attribute name:Attribute value,
	Attribute name:Attribute value,
	Attribute name:Attribute value
}
</script>
  1. Object Assignment
<script>
	person.name ="xxxx"
</script>
  1. Using a nonexistent object attribute will not report an error, but only undefined
  2. Dynamically delete attributes
<script>
delete person.name
true
person
</script>
  1. Dynamic addition
<script>
	person.newname="xxxx"
</script>
  1. Judge whether the attribute value is in the object xxx in xxx

6. Judge whether a property is the hasOwnProperty() owned by the object itself

control flow

  1. if judgment
  2. loop
<script>
	while(age<10){
		age  = age+1;
	}
</script>
  1. for loop
<script>
	for(let i =0 ; i < 100 ; i++){
		console.log(age)	
	}
</script>
  1. Array loop
<script>
	var list = [1,,2,4,5,5,6,7];
	list.forEach(function(value){
		console.log(value)
	})
	// for (var index in object) num is essentially an index
	for(var num in age){
		if(age.hasOwnProperty(num)){
			console.log("existence")
		}
	}
</script>

Map and Set (new in ES6)

  1. Map
<script>
 	 var names = ["tom" , "toy" , "jack"];
 	 var scores = [100,90,80];
	
	var map = new Map([["tom",80],["toy" , 90 ],["jack",80]]);
	map.set("admin",84);
	var name = map.get("tom");
	console.log(name);
	
</script>
  1. Set
    The biggest feature of Set is that it can be de duplicated
<script>
	var set =  new Set([1,1,1,1,3]);               //              1 3
	set.add(2);//add to
	set.delete(1)//delete
	set.has(30);//Include an element
</script>
  1. iterator
	
	//Traversal array	
	var arr = [1,2,3]
	for (var x of arr){
		console.log(x) //x is the subscript
	}
	// Traversal map
	var map = new Map([["tom",80],["toy" , 90 ],["jack",80]]);
	for (let x of map){
		console.log(x)
	}
	
	//Traversal Set
	var set = new Set([4,5,6])
	for (let x of set){
		debugger; //Stop executing JavaScript and call the debug function if available
		console.log(x)
	}

4. Function

  1. Define function
    A JavaScript function is a block of JavaScript code that can be executed when called.
<script>
 	function abs(x){
		if (x > 0){
			return x;
		}
		else if (x < 0){
			return -x;
		}
	}
	//Equivalent to
	var abs = fuction(x){
	if (x > 0){
		return x;
		}
	else if (x < 0){
			return -x;
		}
	}
	
</script>
  1. arguments contains all parameters. Sometimes, if we need to use redundant parameters, we need to exclude the existing parameters·
<script>

	var abs = fuction(x){
	console.log("x==>" + x);

	for ( var i = 0 ; i<arguments.length; i++){
		console.log(argunments[i]);
	}
	if (x > 0){
		return x;
		}
	else if (x < 0){
			return -x;
		}
	}
	

</script>
  1. rest
    The new feature introduced in ES6 obtains all parameters except the defined parameters -
<script>

	var abs = fuction(a, b,c,d ,...rest){
		console.log(a);
		console.log(b);
		console.log(c);
		console.log(d);
		console.log(rest);  //All redundant parameters will be printed here
	}
	
// rest can be written in the last parameter and must use express

</script>
  1. function call
<!DOCTYPE html>
<html>
<head>
<script>
function mytest(studentList){
	for i in studentList {
		console.log(i);
		document.write(i); // After the HTML document is fully loaded, use document Write() will delete all existing HTML:
		window.alert(i); // alert uses the warning box to pop up the display data
	}	
}
function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";// Modify the element information of the specified id
}
</script>
</head>

<body>

<h1>A web page</h1>
<p id="demo">A paragraph</p>
<button type="button" onclick="myFunction()">have a try</button>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript function</h2>

<p>This example calls the function to convert Fahrenheit to Celsius:</p>

<p id="demo"></p>
<p id="test"></p>
<script>
function toCelsius(f) {
    return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius(86);

function click1(a){
	//document.write(a);
    for (i of a) {
    	document.getElementById("test").innerHTML = i;
    }
    
}
</script>
<button onclick = "click1(['1','2','3'])" >Click Me</button>


</body>
</html>

Scope of variable

Note the difference between global and non global variables
Others are no different from java

javascript object

Objects, attributes and methods in real life
In real life, the car is an object.
Cars have attributes such as weight and color, as well as methods such as starting and stopping:

JavaScript object
JavaScript variables are containers for data values.

This code assigns a single value (porsche) to a variable named car

var car = "porsche";

Objects are also variables. But objects contain many values.

This code assigns multiple values (porsche, 911, white) to the variable named car:

var car = {type:"porsche", model:"911", color:"white"};

Object method

Method is to put the function in the object. The object has only two things, attributes and methods

<script>

	var person = {
			name:"xx",
			brith:"2020",
			age:fuction(){
				var now = new Date().getFullYear();
				return now-this.brith;
			}
		}


	//Method of disassembling the upper edge
	fuction getAge(){
	var now = new Date().getFullYear();
				return now-this.brith;
	}
	
		var person = {
			name:"xx",
			brith:"2020",
			age:getAge
			}
		}	
person.name
person.age()

</script>

Access object properties
Use person Reference object method in property mode

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Object properties</h1>

<p>There are two different ways to access object properties.</p>

<p>use person.property or person["property"]. </p>

<p id="demo"></p>

<script>
// Create object:
var person = {
    firstName: "Bill",
    lastName : "Gates",
    id       :  12345
};

// To display data in an object:
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>

</body>
</html>

Use the person ["property"] method

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Object properties</h1>

<p>There are two different ways to access object properties.</p>

<p>You can use person.property or person["property"]. </p>

<p id="demo"></p>

<script>
// Create object:
var person = {
    firstName: "Bill",
    lastName : "Gates",
    id       :  12345
};

// To display data in an object:
document.getElementById("demo").innerHTML =
person["firstName"] + " " + person["lastName"];

</script>

</body>
</html>

Call object method
objectName.propertyName or objectname ["propertyName"]

example

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Object method</h1>

<p>An object method is a function definition stored as an attribute value.</p>

<p id="demo"></p>

<script>
// Create object:
var person = {
    firstName: "Bill",
    lastName : "Gates",
    id       : 12345,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

// To display data in an object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>

alpply

This method is supplemented later

Internal object

Standard object: number string bool function object undefined function number string

  1. Date
<script>
	var now = new Date();
	now.getFullYear();
	now.getMonth();
	now.getDate();
	now.getDay(); // What day is today?
	now.getHours();
	now.getMinutes();
	now.getSeconds();
	now.getTime(); // time stamp

</script>

javaScript events

Usually, when an event occurs, the user wants to do something.

JavaScript allows you to execute code when an event is detected.

With JavaScript code, HTML allows you to add event handlers to HTML elements.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript event</h1>

<p>Click the button to display the date.</p>

<button onclick="displayDate()">What's the time?</button>

<script>
function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>

</body>
</html>

Use this InnerHTML can directly change the content of its own elements

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript event</h1>

<button onclick="this.innerHTML=Date()">What's the time?</button>

</body>
</html>

Common html events

onchange HTML element has been changed
The onclick user clicked on the HTML element
onmouseover users move their mouse over HTML elements
onmouseout user moves mouse over HTML element
onkeydown the user presses the keyboard key
onload browser has finished loading the page

JSON

What is json?
In JavaScript, any js supported type

  • All objects use {}
  • Arrays have []
  • All key value pairs use key value
<script>
	var user ={
		name : "xxx",
		age : 18
	}
//Object to json string
var jsonUser = JSON.stringfy(user)
//Convert JSON string to object
var obj  = JSON.parse('{"name" : "xxx" , "age" : "18"}')
</script>

Keywords: Javascript

Added by VDarkAzN on Wed, 19 Jan 2022 14:15:04 +0200