Summary of Javascript objects, attributes and methods (review)

Summary of Javascript objects, properties and methods

1. What is JavaScript?

javaScript ---- is an object-oriented scripting language.

Object oriented is a kind of programming thought, which can't be seen or touched. It can only be realized and proved by practical action.

The idea of object-oriented programming is the sublimation of the idea of process oriented programming.

Process oriented thinking

Script - a written program can run immediately in the running environment without intermediate conversion. javaScript,SQL

Independent javascript file linking method < script SRC = "mytest. JS" > < / script >


2. Variables in JavaScript

         1. Variable is the smallest unit in program operation.

         2. The stored variables are containers. In order to reduce the running space of the program.

         3. Composition of variables

                   1. Data type [determine the data type according to the specific data value given during assignment]

                   2. Name

                   3. Data value

                   4. Scope [validity of variables in different locations]

          4. Define variables

  1. Define variables through var keyword
  2. Format: var variable name = data value;
  3. var variable name;
  4. Multiple variables VaR, test1, hello1 can be defined at one time;

2.1 data types in JavaScript

1. The data type of the JavaScript variable,

Not determined when declaring / defining variables,

The data type of a javaScript variable is after assignment,

The data type of the variable is determined according to the specific data value given.

2. Specific data types of JavaScript

  • String (string)
  • Number
  • Boolean
  • Array
  • Object
  • Empty (Null)
  • Undefined

JavaScript has dynamic types

The data type of javaScript variable is not determined when declaring / defining the variable. The data type of javaScript variable is determined according to the specific data value given after assignment

        1. String (string)

A string is a variable that stores characters (such as "Bill Gates").

A string can be any text in quotation marks. You can use single quotation marks or double quotation marks;


For example:

var carname="Volvo XC60";

var carname;

carname='Volvo XC60';

You can use quotation marks in a string as long as they do not match the quotation marks surrounding the string


         2. Number

JavaScript has only one numeric type. Numbers may or may not have a decimal point.

Extremely large or small numbers can be written by scientific (exponential) counting

         3.JavaScript Boolean

There are only two values: true/false

It is often used for judgment

         4. Array type [array]

An array is a data type that holds a set of data values.

Array definition:

1. First define, then assign

   var arr1=new Array(); // Define / create

Array assignment -- by subscript

Understand subscript: the position of specific data value in the array [starting from 0]

Format: array variable name [subscript] = data value;




2. Definition + assignment

  var arr2=new Array(“zhangsan”,23,true); // Definition + assignment

Value of array: array name [subscript]


length attribute of array: get the number of elements in the array

         5.JavaScript object

By "{}", where key value pairs are used [Title: page / key: value]

var user={userid:1001,


useraddress: "Xi'an",


                 return "hello";



          6. Undefined in JavaScript

Undefined -- no value

          7. null in JavaScript

Generally, if the defined variable is uncertain about the data type, it can be replaced by null and empty type.

          var  a=null;

          var  b=null;


3.JavaScript functions

Functions are also called methods.

A function is actually a code set that implements a related function [code block {}]

Syntax format of function:

Function [function name] ()



Function is the keyword that declares / defines the function

Function name

. the functions are divided into [Famous functions, anonymous functions] according to whether they have names

function test1(){
alert("named function");

alert("anonymous function");

() --- parameter list [there can be parameters, multiple parameters or no parameters, but ()] cannot be omitted]

Parameter introduces data outside the current function into the current function for operation [find help]

{} -- code block that implements specific functions

4.JavaScript comments


Note -- mark [for future reference]

Interpretation -- Description

Note - mark out the program and explain the meaning.

Role of notes:

1. Mark out the program, explain the meaning, and make it convenient for others or yourself to check in the future.

  2. Debugging program

Characteristics of annotation: the content of annotation will not be executed

There are two types of comments in Javascript:

1. Single line notes [one line at a time]

//Annotated content [own text / code to explain the meaning]

Where it appears [1. The line above the current line code 2. The line after the current line code]

For example:

var num1=100; / / numeric type of integer

var num2=12.5; // Numeric type of decimal

//Integers and decimals are unified into digital Number

var num3=num1+num2;

2. Multi line annotation [multi line annotation at one time]


*Annotated content

*[own text / code to explain the meaning]

*/ / single line comments can be included


Do not use javascript syntax annotations to annotate html tags

   5.JavaScript operator

1. Arithmetic operators +, -, *, /,%, + +, --.

2. Comparison operator = = = =======   >  <  >=  <=

The result must be Boolean

3. Logical operator | & &!

The operation data and operation results are boolean

3 || 5---???

(3>5)  ||  (3<5)------true

Truth table

a=true   b=false




a  ||  b---true

a  &&  b---false

!a ---false

b  ||  a---true

b  &&  a---false

!b ---true

a  ||  a---true

a  &&  a---true


b  ||  b---false

b  &&  b---false


4. Conditional operator [(judgment expression)? Numeric value 1: numeric value 2] ()?:

var  iablename=()?value1:value2

5.typeof operator -- detect the data type of the variable

typeof  ___

5.JavaScript process control statement

Sequential structure # line by line from top to bottom

Select structure # selectively execute a part of the program

    1.if statement structure




3.if(){}else if(){}else if(){}...else{}

4. Nesting of if statements

    2.Switch statement structure

switch statements are used to perform different actions based on different conditions.


Switch (expression n){
case constant value 1:
Execute code block 1 # break;
case constant value 1:
Execute code block 2 break;


case constant value n:
Execute code block n
The result of the expression does not match the constant value after case;


How it works: first set the expression n (usually a variable). The value of the expression is then compared with the value of each case in the structure. If there is a match, the code block associated with the case is executed. Use # break # to prevent the code from automatically running to the next case.

3. Circulation structure

       1.for loop


for (statement 1; statement 2; statement 3){
Executed code block

Execute starts before statement 1 (code block) starts [initial conditions]

Statement 2: define the condition [judgment condition] for running a loop (code block)

Statement 3: [loop increment / decrement] is executed after the loop (code block) has been executed


The JavaScript for/in statement loops through the properties of the object

for (save attribute variable # in # object){

Object name [variable to save attribute value]// Attribute value


 var user={id:1001,name:"zhangsan",age:23};
  var att=""; //Variables that hold attributes
  for(att in user){

3.while loop


while (judgment condition){
Code to execute

  1. The initial value needs to be defined outside the while syntax
  2. The code that controls the increment / decrement of the loop needs to be written after the "code to be executed". If not, it is an dead loop.

For example:

var  arr1=new Array(6,5,4,3,2,1);
				var i=0; // Initial value
					 document.write("<h"+arr1[i]+">test for loop</h"+arr1[i]+">");

4. do{}while loop


What is the difference between while and do{}while()?

While is to judge before execution, do{}while() executes before judgment, and do{}while() executes more than once under the same conditions as while.

The difference between while/do{}while() and for

for -- you need to know the number of cycles clearly when executing

The number of {/ while ()} loops that do not need to be known.


Code to execute
} while (judgment condition);

1. The initial value needs to be defined outside the while syntax

2. The code that controls the increment / decrement of the loop needs to be written after the "code to be executed". If not, it is an dead loop.

What is the difference between while and do{}while()?

While is to judge before execution, do{}while() executes before judgment, and do{}while() executes more than once under the same conditions as while.

The difference between while/do{}while() and for

for -- you need to know the number of cycles clearly when executing

The number of {/ while ()} loops that do not need to be known.

6. Statements in JavaScript

  1. Sequential structure
  2. Select structure
  3. Cyclic structure

3.5 break and continue statements [return]

               (1)break;---- Interrupt [switch \ cycle]

                  (2).continue ---- continue [cycle {end the current cycle and enter the next cycle}]

7. Objects in JavaScript

            1. Built in objects

1.1 advanced object String Number Date Array

1.2 Dom object

1.3Bom object window

              2. Custom objects

JavaScript objects are data with attributes and methods [functions].

Car [object] - weight, length, width, height, brand, color [properties]

Car [object] - forward, backward, brake [method [function]]

An object is also a variable, but an object can contain multiple values (multiple variables)

var car = {type:"Fiat", model:500, color:"white"};

JavaScript objects are containers for variables and methods

create object

var object name = {attribute name: attribute value,..., method name: function() {},...};

The attribute name does not need quotation marks, the attribute value [string, time and date] needs quotation marks, and other values do not need quotation marks.

var person = {
    firstName : "John",
    lastName  : "Doe",
    age       : 50,
    eyeColor  : "blue"

               3. Access to properties and methods in objects


 1. Property access in object

Format: object name Attribute name;

Object name ['attribute name'] / object name ['attribute name']

2. Method access in object

Format: object name Method name;

8. Classification of variables

1. Global variable --- a variable other than the object

(1) The current object is outside the function

(2) In the function where the current object is located

2. Local variable --- in the object, in the function of the object, and the parameters of the function

(1) Local variables in the function in the current program

(2) In the function of the object -- only the function of the current object can be accessed

3. Variable other than method in object [object attribute] - object name Attribute name

4. Parameters of function

     (1.) Parameters of the function of the current program = = = local variables in the function of the current program

      (2.) The method parameter of the current object = = = in the function of the object.

9. Objects in JavaScript


1.1 custom objects

1.2 built in objects

            1. Advanced object

            2.dom object


1.3 JavaScript advanced objects

           1. establish

           2. Call the properties and methods of the object

           3. matters needing attention

               1. String object (string)

A string can use single or double quotation marks:

                    var carname="Volvo XC60";

                     var carname='Volvo XC60';

1.1String creation

  1. var str1="hello,world" through direct assignment;

     2. Through the constructor of string, @ new String(value);    var str2=new String("hello,world");

1.2 common attributes and methods of string

(1) length attribute --- calculate the length of the string

(2)charAt(index) -- get the character at the specified position in the string

                                           var str1="hello,world";

                                           var ch2=str1.charAt(6);

(3)indexOf() -- get the first occurrence position of the specified character / string in the original string. If not, get - 1

(4)lastIndexOf() gets the last occurrence position of the specified character / string in the original string. If not, it gets - 1

(5) substring(start,end) -- intercept string

(6)replace(old,new) method replaces some characters with others in the string.

(7) string case conversion uses the function (uppercase) toUpperCase() / (lowercase) tolower case()

(8) split converts a String into a String array through the specified separator [split String]

Special characters




Single quotation mark


Double quotation mark


Inclined rod


Line feed







 var info="zhangsan:say\"hello\"";

10.Number object

JavaScript has only one numeric type.

JavaScript numbers can be written with or without a decimal point:

  1. var pi=3.14; / / use decimal point

  2. var x=34; / / do not use decimal point

Maximum or minimum numbers can be written by scientific (exponential) counting:

  1. var y=123e5;    // 12300000

  2. var z=123e-5;   // 0.00123


Integer (without decimal point or exponential counting method) can be up to 15 digits.

The maximum number of decimal places is 17, but floating-point operations are not always 100% accurate:

var num1=10/3;    //3.3333333333335

Octal and hexadecimal

If the prefix is 0, JavaScript interprets the numeric constant as an octal number, and if the prefix is 0 and "x", it is interpreted as a hexadecimal number.

  1. var y = 0377; // Octal 255

  2. var z = 0xFF; / / hex 255

Note: we should not use "0" / "0x" at the beginning when assigning a numeric variable

Infinity and {infinitesimal (- infinity)

In JavaScript, all JavaScript numbers are 64 bits. When the number operation result exceeds the upper limit of the number represented by JavaScript (overflow), the result is a special Infinity value, which is represented by Infinity in JavaScript. Similarly, when the value of a negative number exceeds the range of negative numbers that JavaScript can represent, the result is negative Infinity, which is represented by - Infinity in JavaScript. The behavior of Infinity is consistent with what we expect: Based on their addition, subtraction, multiplication and division, the result is still Infinity (of course, their sign is retained).

Dividing by 0 also produces Infinity: var num2=10/0;

NaN - non numeric value [not a Number]

The NaN attribute is a special value that represents a non numeric value. This property indicates that a value is not a Number. You can set the Number object to this value to indicate that it is not a numeric value.

You can use the isNaN() global function to determine whether a value is a NaN value.

var x = 1000/"Apple";

alert(isNaN(x)); / / true [not a number]

var x2 = 1000 * "1000";    //1000000

alert(isNaN(x2)); //false [is a number]

Creation of digital objects

    1. Direct assignment of variables

     2. By constructor

//Direct assignment of variables

var testnum1=10.558;

//By constructor

var testnum2=new Number(10.558);

Common properties and methods of digital objects

  1. MAX_VALUE -- the maximum number that can be represented in JavaScript: number MAX_VALUE
  2. MIN_VALUE -- the smallest number that can be represented in JavaScript: number MIN_VALUE


toFixed(); Rounding retains the specified number of decimal places

var testnum2=new Number(10.558);

//toFixed(); Rounding retains the specified number of decimal places

var res1=testnum2.toFixed(2); //10.56

Throw an exception RangeError when num is too small or too large. A value between 0 and 20 will not throw the exception. Some implementations support a larger or smaller range of values.

When the object calling this method is not Number, a TypeError exception is thrown

The toString() method converts a Number object into a string and returns the result.

11.JavaScript Array

The function of array objects is to use separate variable names to store a series of values

Array creation:

 1. Define before assign

var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

2. Definition + assignment

var myCars=new Array("Saab","Volvo","BMW");

3. Literal assignment

var myCars=["Saab","Volvo","BMW"];  //[] = array

4. Array value --- format: array name [subscript]

var myCars=["Saab","Volvo","BMW"]; 
myCars[2];    //BMW

You can have different objects in an array

var stu={stuid:1001,
			alert("custom object");
var myarr = new Array();

Array methods and properties

length Get the number of array elements  
concat() Merge two arrays  
join() Use the elements of the array to form a string  
pop() Deletes the last element of the array  
shift() Delete the first element of the array  
push() Adds a new element to the end of the array  
unshift() Add a new element at the beginning of the array  
splice() Adds or removes an element at a specified position in the array  
reverse() Reverses the order of the elements in an array  
slice(start,end) Select elements from an array  

sort() array sort

sort() numeric sort

(in ascending alphabetical order)

(ascending / descending in numerical order)


splice(index,howmany[,item1,...,itemx]): add or delete elements to the array and return the deleted elements.

Where index is the location of the element to be added or deleted. It can be negative, which counts down from the end.

howmany is the number of elements to be deleted. When its value is 0, no element will be deleted.

var ab3=new Array(1,2,3,4,5,6,7);
			ab3.splice(3,3,["Starting from the third element in the array, delete three elements and add an element at the position of the third element"]);

12.JavaScript Boolean [note the difference between Boolean object and Boolean value]

 1. Create boolena object

Boolean is a transformation function. That is, you can pass any value to boolean type, that is, return true and false

1.1 direct assignment

var bool=false;
var bool=true;

1.2 create boolean object through constructor

You can convert any value to a boolean type by creating a Boolean object through the constructor


Boolean conversion rules
data type Value converted to true Value converted to false
Boolean true false
String Any non empty string ""
Number Any non-zero value 0 and NaN
Object  Any object (including boolean object) null
Undefined Do not return true undefine


be careful:

1. Create a Boolean object by means of new Boolean(), and get the Boolean object. Get the original value of Boolean by means of Boolean().

2. Whether it is a boolean object or not, as long as it is an object, it will be converted into a boolean value in the judgment condition of the if statement and must be true. The boolean data value in the boolean object can be obtained through the valueOf() method provided by the boolean object.

13.JavaScript Date

 1. Creating Date Objects

    1.1 new Date(); // Current system time

1.2 new Date(milliseconds) / / the number of milliseconds difference between January 1, 1970

var date2=new Date(1000);

1.3 new Date(dateString) / / set date

var date3=new Date("2018/12/1 12:29:30");

1.4 new Date(year, month, day, hours, minutes, seconds, milliseconds) / / set the date

var date4=  new Date(3030, 3, 3, 3, 3, 3, 3000);

  2. Common methods of date


getTime() Returns the number of milliseconds since January 1, 1970.  
getFullYear() Get year  
getMonth() Get the month [starting from 0, we need + 1]  
getDate() Gets the number of days in the month  
getDay Get week  
getHours() Get hours  
getMinutes() Get minutes  
getSeconds() Get seconds  

set up:

setFullYear(y,m,d)  Set specific date  
setMonth() sets the month [counting from 0, we need - 1]  
setDate() Set the number of days in the month  
setDay() Set week  
setHours() Set hours  
setMinutes() Set minutes  
setSeconds() Set seconds  
setTime() Set the number of milliseconds, get the number of milliseconds set from January 1, 1970, and give the time and date again  

3. Comparison of two dates

Date objects can also be used to compare two dates.

The following code compares the current date with January 14, 2100

var x=new Date();
x.setFullYear(2100,0,14);//Set a time for comparison
var today = new Date(); //Get the time and date of the day
if (x>today){
alert("Today is before January 14, 2100");
alert("Today is after January 14, 2100");

14JavaScript Math (arithmetic)

   1. The Math object is used to perform common math tasks.

Calculation value [constant value]

                 Math.E -- natural constant, which is mathematics One in constant , it's a Infinite acyclic decimal , and Transcendental number , the value is about 2.718281828459045.
                 Math.PI - pi

         2. Arithmetic method

(1)max() returns the larger of two given numbers

(2)min() returns the smaller of two given numbers

(3)random() returns a random number between 0 and 1.

(4) the nearest integer of round()

document.write("<h1>Natural constant=="+Math.E+"</h1>");
document.write("<h1>square root=="+Math.sqrt(9)+"</h1>");
document.write("<h1>Cube root=="+Math.cbrt(8)+"</h1>");
document.write("<h1>pow =="+Math.pow(2,3)+"</h1>");
document.write("<h1>random number=="+Math.random()+"</h1>");
document.write("<h1>Nearest integer=="+Math.round(-12.6)+"</h1>");
document.write("<h1>Maximum number=="+Math.max(12,34,8)+"</h1>");
document.write("<h1>Minimum decimal=="+Math.min(12,34,8)+"</h1>");

15.JavaScript RegExp object

RegExp: short for regular expression.

RegExp is a format used to retrieve and judge text data. It is often used in data verification.

   1. Create format:

var patt=new RegExp(pattern,modifiers);

var patt=/pattern/modifiers; [not recommended]

Note: when using constructors to create regular objects, you need regular character escape rules (preceded by backslash \).

var re = new RegExp("\\d+"); 


Matches any invisible characters, including spaces, tabs, page breaks, and so on. Equivalent to [\ f\n\r\t\v].


Matches any non word characters. Equivalent to "^ uz-0 [- Za]"


Match input word line beginning


Match end of input line


Any time


Zero or once


n times of matching determination


Match at least n times


At least n matches and at most m matches

. point



Match a numeric character


Matches any word characters that include underscores


One or more times (greater than or equal to 1 time)


Character range. Matches any character within the specified range


Negative character range. Matches any character that is not within the specified range

   2. String of commonly used regular expressions

I. expression of check number

        1. Number: ^ [0-9]*$

        2. n-digit number: ^ \ d{n}$

        3. At least n digits: ^ \ d{n,}$

        4. m-n digits: ^ \ d{m,n}$

        5. Numbers starting with zero and non-zero: ^ (0| [1-9] [0-9] *)$

        6. Non zero digits with up to two decimal places: ^ ([1-9] [0-9] *) + (. [0-9] {1,2})$

        7. Positive or negative numbers with 1-2 decimal places: ^ (\ -)? \d+(\.\d{1,2})?$

        8. Positive, negative, and decimal numbers: ^ (\ - | \ +)? \d+(\.\d+)?$

        9. Positive real number with two decimal places: ^ [0-9] + (. [0-9] {2})$

        10. Positive real numbers with 1 ~ 3 decimal places: ^ [0-9] + (. [0-9] {1,3})$

        11. Non zero positive integer: ^ [1-9]\d * $or ^ ([1-9] [0-9] *) {1,3} $or ^ \ +? [1-9][0-9]*$

        12. Non zero negative integer: ^ \ - [1-9] [] 0-9 "* $or ^ - [1-9]\d*$

        13. Nonnegative integer: ^ \ D + $or ^ [1-9]\d*|0$

        14. Non positive integer: ^ - [1-9]\d*|0 $or ^ (- \ d+)|(0 +))$

II. Expression of check character

                  1. Chinese characters: ^ [\ u4e00-\u9fa5]{0,}$

                  2. English and figures: ^ [A-Za-z0-9] + $or ^ [A-Za-z0-9]{4,40}$

                  3. All characters with length of 3-20: ^ {3,20}$

                  4. String composed of 26 English letters: ^ [A-Za-z]+$

                  5. String consisting of 26 uppercase English letters: ^ [A-Z]+$

                  6. String consisting of 26 lowercase English letters: ^ [a-z]+$

                  7. String composed of numbers and 26 English letters: ^ [A-Za-z0-9]+$

                  8. String consisting of numbers, 26 English letters or underscores: ^ \ W + $or ^ \ w{3,20}$

                  9. Chinese, English, figures including underscores: ^ [\ u4E00-\u9FA5A-Za-z0-9_]+$

                  10. Chinese, English, numbers but excluding underscores and other symbols: ^ [\ u4E00-\u9FA5A-Za-z0-9] + $or ^ [\ u4E00-\u9FA5A-Za-z0-9]{2,20}$

                  11. You can enter ^% & '; =$\ "Equal characters: [^% & '; =? $\ x22] + 12 it is forbidden to enter characters containing ~ [^ ~ \ x22]+


3, Special requirements expression

                 1. Email address: ^ \ w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$

                 2. Domain name: [a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62}) + /?

                 3. InternetURL: [a-zA-z]+://[^\s] * or ^ http: / / ([\ W -] + \.)+ [\w-]+(/[\w-./?%&=]*)?$

                 4. Mobile phone number: ^ (13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$

                 5. Telephone numbers ("XXX-XXXXXXX", "XXXX-XXXXXXXX", "XXX-XXXXXXXX", "XXX-XXXXXXXX", "XXXXXXX" and "XXXXXXXX): ^ (\ (\ d{3,4}-)|\d{3.4}-)?\d{7,8}$

                 6. Domestic telephone number (0511-4405222, 021-87888822): \ D {3} - \ D {8} \ D {4} - \ D {7}

                 7. ID number (15 and 18 digits): ^\d{15}\d{18}$

                 8. Short ID card number (ending with numbers and letters x): ^ ([0-9]){7,18}(x|X)$ Or ^ \ d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}$

                 9. Whether the account number is legal (starting with a letter, 5-16 bytes are allowed, and alphanumeric underscores are allowed): ^ [a-za-z] [a-za-z0-9] {4,15}$

                 10. Password (starts with a letter, is between 6 and 18 in length, and can only contain letters, numbers and underscores): ^ [a-zA-Z]\w{5,17}$

                 11. Strong password (must contain a combination of upper and lower case letters and numbers, cannot use special characters, and the length is between 8-10): ^ (? =. * \ d) (? =. * [A-Z]) (? =. * [A-Z]) (? =. * [A-Z]) {8,10}$

                 12. Date format: ^ \ d{4}-\d{1,2}-\d{1,2}

                 13. 12 months of a year (01-09 and 1-12): ^ (0? [1-9] |1 [0-2])$

                 14. 31 days of a month (01-09 and 1-31): ^ ((0? [1-9]) | (1 | 2) [0-9]) | 30 | (31)$

Common operation methods of RegExp:

1. The test () method searches for the value specified by the string and returns true or false according to the result

2. The exec () method retrieves the specified value in the string. The return value is the value found. If no match is found, null is returned.

For example:

<!DOCTYPE html>
		<meta charset="utf-8">
			//1. The test () method searches for the value specified by the string and returns true or false according to the result
			var reg1=new RegExp(/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/);
			var phoneNum="100000";
			var res1=reg1.test(phoneNum);
			//2. The exec ("searched data value") method retrieves the specified value in the string. The return value is the value found. If no match is found, null is returned.
			var reg2=new RegExp("134");
			var text1="hello13474682774world";
			var res2=reg2.exec(text1);
				document.write("<h1>existence,The result is=="+res2+"</h1>");

   16.JavaScript type conversion -- data type conversion

1. By using JavaScript functions, for example: toString()

2. Automatically convert through JavaScript itself. For example: VAR num1=100;  var res=num1+”hello”;

      1. Convert numbers to strings

var  num1=100;
			var str1=new String(num1); //String Object
			var str11=String(num1); //String value
//2. The number method toString() has the same effect.
			var str2=num1.toString(); //String value
//3. ToFixed (number of decimal places) converts a number into a string, and there is a number of specified digits after the decimal point of the result.
			var  num1=100;
			var str3=num1+"";

2. Convert a string containing a numeric value to a number

<script type="text/javascript">
 	 	var  str1="25";
 	 	//1. The global method Number() can convert a string to a number.
 	 	var  num1=new Number(str1); //Number Object
 	 	var  num11=Number(str1); //Number value
 	 	document.write("<h1>num1==="+num1+",type=="+typeof num1+"</h1>");
		document.write("<h1>num11==="+num11+",type=="+typeof num11+"</h1>");
 	 	//2. String containing numeric value * 1
 	 	var  num2=str1*1; //Number value
 	 	document.write("<h1>num2==="+num2+",type=="+typeof num2+"</h1>");
 	 	//3. Unary operator+
 	 	var  num3= +str1; //Number value
 	 	document.write("<h1>num3==="+num3+",type=="+typeof num3+"</h1>");

3. Convert Boolean values to strings

<script type="text/javascript">
 		//1. The global method String() can convert Boolean values to strings.
 		var boo1=true;
 		var str1=new String(boo1);
 		var str11= String(boo1);
 		document.write("<h1>str1==="+str1+",type=="+typeof str1+"</h1>");
		document.write("<h1>str11==="+str11+",type=="+typeof str11+"</h1>");
 		//2. The boolean method toString() has the same effect.
 		var str2=boo1.toString();
 		document.write("<h1>str2==="+str2+",type=="+typeof str2+"</h1>");

4. Convert string to Boolean

<script type="text/javascript">
 		 //1. The empty string is converted to false
 		var str1=""; 
 		var  boo1=new Boolean(str1);  //Boolean Object
 		var  boo11=Boolean(str1);  //Boolean vaue
 		document.write("<h1>boo1==="+boo1+",type=="+typeof boo1+"</h1>");
		document.write("<h1>boo11==="+boo11+",type=="+typeof boo11+"</h1>");
 		//2. The non empty string is converted to true
 		var str2="asgsde"; 
 		var  boo2=new Boolean(str2);  //Boolean Object
 		var  boo22=Boolean(str2);  //Boolean vaue
 		document.write("<h1>boo2==="+boo2+",type=="+typeof boo2+"</h1>");
		document.write("<h1>boo22==="+boo22+",type=="+typeof boo22+"</h1>");
 		//Note: a string with a value of false is converted to a boolean value of true, because a string with a value of false is also a non empty string
 		var str3="false";
 		var  boo3=Boolean(str3);  //Boolean vaue
 		document.write("<h1>boo3==="+boo3+",type=="+typeof boo3+"</h1>");

5. Convert numbers to Booleans

<script type="text/javascript">
 		//1. The number 0 is converted to false
 		var  num1=0;
 		var  boo1=new Boolean(num1);  //Boolean Object
 		var  boo11=Boolean(num1);  //Boolean vaue
		document.write("<h1>boo1==="+boo1+",type=="+typeof boo1+"</h1>");
 		document.write("<h1>boo11==="+boo11+",type=="+typeof boo11+"</h1>");
 		//2. Non-zero numbers are converted to true
 		var  num2=123;
 		var  boo2=new Boolean(num2);  //Boolean Object
 		var  boo22=Boolean(num2);  //Boolean value
		document.write("<h1>boo2==="+boo2+",type=="+typeof boo2+"</h1>");
 		document.write("<h1>boo22==="+boo22+",type=="+typeof boo22+"</h1>");

6. Convert Boolean values to numbers

<script type="text/javascript">
 		var boo1=true;  //true is converted to the number 1
 		var num1=new Number(boo1);
 		var num11=Number(boo1);
 		document.write("<h1>num1==="+num1+",type=="+typeof num1+"</h1>");
		document.write("<h1>num11==="+num11+",type=="+typeof num11+"</h1>");
 		var boo2=false;  //false is converted to the number 0
 		var num2=new Number(boo2);
 		var num22=Number(boo2);
 		document.write("<h1>num2==="+num2+",type=="+typeof num2+"</h1>");
		document.write("<h1>num22==="+num22+",type=="+typeof num22+"</h1>");
 		//Multiply by 1 [* 1]
 		var num3=boo1*1;
 		document.write("<h1>num3==="+num3+",type=="+typeof num3+"</h1>");
 		var num4=boo2*1;  
 		document.write("<h1>num4==="+num4+",type=="+typeof num4+"</h1>");

7. Convert date to number

<script type="text/javascript">
		var date1=new Date();
		var num1=new Number(date1);
		var num11= Number(date1);
		document.write("<h1>num1==="+num1+",type=="+typeof num1+"</h1>");
		document.write("<h1>num11==="+num11+",type=="+typeof num11+"</h1>");
		//Note: after the date is converted to a number, it is the number of milliseconds from 1970-1-1 to the current date
		//The date method getTime() has the same effect.
		var num2= date1.getTime();
		document.write("<h1>num2==="+num2+",type=="+typeof num2+"</h1>");

8. Convert numbers to dates

<script type="text/javascript">
		//Convert numbers to dates
		var num1=1605844538320;
		var date1=new Date(num1); //Object
		var date11=Date(num1); //string
		document.write("<h1>date1==="+date1+",type=="+typeof date1+"</h1>");
		document.write("<h1>date11==="+date11+",type=="+typeof date11+"</h1>");

9. Convert date to string

<script type="text/javascript">
 		//The global method String() can convert the date to a string.
 		var date1=new Date();
 		var str1=new String(date1); 
 		var str11=String(date1);
 		document.write("<h1>str1==="+str1+",type=="+typeof str1+"</h1>");
		document.write("<h1>str11==="+str11+",type=="+typeof str11+"</h1>");
 		//The Date method toString() has the same effect.
 		var str2=date1.toString();
 		document.write("<h1>str2==="+str2+",type=="+typeof str2+"</h1>");

10. Convert string to date

<script type="text/javascript">
 		var str1="2020-11-20 12:11:30";
 		var date1=new Date(str1);
 		document.write("<h1>date1==="+date1+",type=="+typeof date1+"</h1>");

Note: the string contains string data in time and date format

17.DOM object

DOM--Document Object Model

When a web page is loaded, the browser creates a document object model of the page.

The HTML DOM model is constructed as a tree of objects

1. Functions that DOM can accomplish

1.JavaScript can change all HTML elements in the page

2.JavaScript can change all HTML attributes in the page

3.JavaScript can change all CSS styles in the page

4.JavaScript can respond to all events in the page

2. Find HTML elements

To do this, you must first find the element. There are three ways to do this:

2.1 getElementById(id attribute value); Find HTML elements by id

2.2 getElementsByTagName (tag name) finds HTML elements by tag name

2.3 getElementsByClassName(class attribute value) find HTML elements by class name

3.JavaScript can change all HTML elements [text content of elements] in the page

innerHTML attribute -- changes the text content of HTML elements in the page

innerText attribute -- changes the text content of HTML elements in the page

4.JavaScript can change all HTML attributes in the page

Attributes are available in both html and css.

Attributes in HTML - are additional information that explains to the browser when running HTML tags.

It often appears in the start tag of html. If there are multiple middle tags, separate them with spaces

1. Use the style attribute in the html start element

2. In the < style > element and ". css" file

Control the format of HTML attributes:

dom object Specific html attribute name = attribute value corresponding to attribute name;

			function testattribute(){
				//dom object Specific html attribute name = attribute value corresponding to attribute name;
				var imgdoc=document.getElementsByTagName("img")[0];
				//alert(imgdoc); [object HTMLImageElement]
				//Imgdoc -- DOM object
				//src -- specific html attribute name
				//"imgs/avatar2.png" -- the attribute value corresponding to the attribute name;

5.JavaScript can change all CSS styles in the page

6. Control events

HTML events are "things" that happen on HTML elements.

When using JavaScript in HTML pages, JavaScript can "cope" with these events.

HTML events

Common HTML events

event describe
onchange The HTML element has been changed
onclick The user clicked on an HTML element
onmouseover The user moves the mouse over the HTML element
onmouseout The user moves the mouse over the HTML element
The user presses the keyboard key
onload The browser has finished loading the page

 3. onchange event, triggered when the user changes the content of the input field

<!DOCTYPE html>
		<meta charset="utf-8">
			function  testonchange(){
				alert("When the input content is changed, it is triggered");
		<input type="text"  value="hello" onchange="testonchange();" />

 4.onfocus triggers when focus is obtained and onblur triggers when focus is lost

<!DOCTYPE html>
		<meta charset="utf-8">
			function  testonfocus(){
				var text1=document.getElementById("text1");
					var text1=document.getElementById("text1");
						var reg1=new RegExp(/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/);
						var val=text1.value;
						var boo=reg1.test(val);
							alert("If the mobile phone number is correct, get the short message verification code");
							alert("The mobile phone number is incorrect, please re-enter");
		<input id="text1" type="text"  value="Please enter your mobile phone number" onfocus="testonfocus();" /><br>

 5.onmouseover and onmouseout events

<!DOCTYPE html>
		<meta charset="utf-8">
				var img1=document.getElementById("img1");
		<img id="img1" src="./imgs/13.jpg" />

  6. The onsubmit event will occur when the confirm button [submit] in the form is clicked.

<!DOCTYPE html>
		<meta charset="utf-8">
			//1. The normal button type="button" cannot trigger the form submission event onsubmit
			//2. The handler function corresponding to the onsubmit event must have a return value [boolean]
			//true - submit form data
			//false --- do not submit form data
			//3. onsubmit="return" processing function of the form;
			function  testOnsubmit(){
				var text1=document.getElementById("text1");
				var pass1=document.getElementById("pass1");
				var span1=document.getElementById("span1");
				var username=text1.value;
				var password=pass1.value;
				if(username=="zhangsan" && password=="123456"){
					alert("Login successful!");
					return true;
					span1.innerHTML="<font color='red' size='7'>Wrong user name and password!</font>";
					return false;
		<span id="span1"></span>
		<form action="#" method="get" onsubmit="return  testOnsubmit();">
			user name:<input id="text1" name="username" type="text" /><br>
			password:<input id="pass1" name="password"  type="password" /><br>
			<input type="button" value="Normal button" /><br>
			<input type="submit" value="land" />

 7. The onkeydown event occurs when the user presses a keyboard key.

<!DOCTYPE html>
		<meta charset="utf-8">
			//1. The testkeydown event needs an event parameter when called
			//2. The keyCode attribute of the event parameter gets the number corresponding to the keyboard key.
			function testKeydown(event){
				var num=event.keyCode;
				if(num==65 || num==37){
					alert("Move left");
				if(num==68 || num==39){
					alert("Move right");
				if(num==87 || num==38){
					alert("Move up");
				if(num==83 || num==40){
					alert("Move down");
	<body onkeydown="testKeydown(event);">

List some event properties


The loading of the image was interrupted.


Element loses focus.


The content of the domain is changed.


The event handle called when the user clicks on an object.


The event handle that is invoked when the user double clicks an object.


An error occurred while loading the document or image.


Element gets focus.


A keyboard key is pressed.


A keyboard key is pressed and released.


A keyboard key is released.


A page or an image is loaded.


The mouse button is pressed.


The mouse is moved.


Move the mouse away from an element.


Move the mouse over an element.


The mouse button is released.


The reset button is clicked.


The window or frame is resized.


The text is selected.


The confirm button is clicked.


The user exits the page.

18. Create a new HTML element

The dom object of the parent element appendChild(node);

Delete the dom object of the element {parent element Removechild (dom object of child element);

<!DOCTYPE html>
		<meta charset="utf-8">
				width: 300px;
				height: 300px;
				background-color: red;
				var addbut=document.getElementById("add");
				var deletebut=document.getElementById("delete");
					//Create element
					var hdom=document.createElement("h1");
					var htext=document.createTextNode("This is an element I added");
					var divdom=document.getElementById("div1");
					var divdom=document.getElementById("div1");
					var hdom=document.getElementById("h1");
					//Delete element
		<div id="div1">
			<h1 id="h1">Test add and remove elements</h1>
		<input id="add" type="button" value="Add element"><br>
		<input id="delete" type="button" value="Delete element"><br>

19. BOM object in JavaScript

Browser Object Model -- browser ObjectModel (BOM)

Window object

1.1 properties


There are three ways to determine the size of the browser window (browser viewports, excluding toolbars and scroll bars).

For Internet Explorer, Chrome, Firefox, Opera, and Safari:

     window.innerHeight - the internal height of the browser window

     window.innerWidth - the internal width of the browser window

For Internet Explorer 8, 7, 6, 5:






1.2 method:

(1) The open () method is used to open a new browser window or find a named window

Format: window open(URL,name,features,replace)


An optional string that declares the URL of the document to be displayed in a new window. If this parameter is omitted or its value is an empty string, no document will be displayed in the new window.


An optional string that is a comma separated list of features, including numbers, letters, and underscores, that declares the name of the new window. This name can be used as the value of the attribute target of the tags < a > and < form >. If this parameter specifies an existing window, the open() method will no longer create a new window, but only return a reference to the specified window. In this case, features will be ignored.


An optional string that declares the characteristics of the standard browser to be displayed in the new window. If this parameter is omitted, the new window will have all standard features.


An optional Boolean value. Specifies whether the URL loaded into the window creates a new entry in the window's browsing history or replaces the current entry in the browsing history. The following values are supported:

True - the URL replaces the current entry in the browsing history.

False - the URL creates a new entry in the browsing history.

Important: please do not confuse the method window Open () and document The functions of the two are completely different. To make your code clear, use window Open() instead of using open().                 



(2) The close () method is used to close the browser window.


The method close() closes the top-level browser window specified by window. A window can be opened by calling self close() or just call close() to close itself.

Only windows opened through JavaScript code can be closed by JavaScript code. This prevents malicious scripts from terminating the user's browser.

(3)JavaScript pop-up method

Create three message boxes in JavaScript: warning box, confirmation box and prompt box.

Warning box: window alert("sometext");

Confirmation box: window confirm("sometext");

When the confirmation card pops up, the user can click "confirm" or "Cancel" to confirm the user's operation.

When you click "confirm", the confirmation box returns true. If you click "Cancel", the confirmation box returns false.

Prompt box: window prompt("sometext","defaultvalue");

When the prompt box appears, the user needs to enter a value, and then click the confirm or cancel button to continue the operation.

If the user clicks OK, the returned value is the entered value. If the user clicks cancel, the return value is null.

Parameter 1 --- prompt information

Parameter 2 --- default value of prompt box

<!DOCTYPE html>
 		<meta charset="utf-8" />
 		<meta name="viewport" content="width=device-width, initial-scale=1">
		<style type="text/css">
				width:300px ;height:300px ;
				background-color: red;
		<script type="text/javascript">
				var butobj =document.getElementById("but1");
				// window.alert("test warning box");
			  var val=window.confirm("Are you sure you want to delete?");
			var divobj=document.getElementById("div1");
			var hobj=document.getElementById("h");
			var butobj2=document.getElementById("but2");
			 var val=window.prompt("Please enter your name","");
					alert("Cannot be empty");
 		<div id="div1">
			<h1 id="h">Test confirmation box</h1>
		<input  type="button" name="" id="but1" value="delete h1" />
		<input type="button" name="" id="but2" value="Test prompt box" />

(4)Window Screen -- screen

 window. The screen object contains information about the user's screen.

  1. Total width and height --- screen width   /  screen.height
  2. Available width and height ----- screen availWidth  / screen.availHeight
  3. Color depth ---- screen colorDepth
  4. Color resolution ---- screen pixelDepth

(5)Window Location --- the address (URL) of the page

Object is used to get the address (URL) of the current page and redirect the browser to a new page.

location. The href property returns the URL of the current page.

location. The pathname property returns the pathname of the URL.

location. The new method of loading the document assign ().

location. The search property is a readable and writable string that can set or return the query part of the current URL (the part after the question mark?).

<!DOCTYPE html>
 		<meta charset="utf-8" />
 		<meta name="viewport" content="width=device-width, initial-scale=1">
		<script type="text/javascript">


<!DOCTYPE html>
		<meta charset="utf-8">
		<title>User login</title>
		<script type="text/javascript">
				var but1=document.getElementById("but1");
				var username=document.getElementById("text1");
				var password=document.getElementById("pass1");
				var span1=document.getElementById("span1");
					var uservalue=username.value;
					var passwordvalue=password.value;
						var span1=document.getElementById("span1");
						span1.innerHTML="<font size='3' color='red'>Wrong user name and password</font>"
				//Focus event
		<table border="1px" >
			<tr align="center">
				<td colspan="2">
					<h1>User login</h><br>
					<span id="span1"></span>
			<tr align="center">
				<td>user name</td>
				<td><input type="text" name="username" id="text1" value="" /></td>
			<tr align="center">
				<td><input type="password" name="password" id="pass1" value="" /></td>
			<tr align="center">
				<td><input type="button" name="butt" id="but1" value="User login" /></td>

<!DOCTYPE html>
		<meta charset="utf-8">
		<script type="text/javascript">
				     var  a=serchvalue.split("=");
					 var username=a[1];
					  var h1obj=document.getElementById("h1");
					  h1obj.innerHTML="welcome"+username+"Login successful";
			<h1 id="h1">Welcome to login</h1>

Note: it will automatically jump to the user login interface;

(6)window.location.href attribute

window.location.href can also be written as window location. href=("url ?string "); This form: (?: separator)

<!DOCTYPE html>
		<meta charset="utf-8">
		<script type="text/javascript">
		document.write("<h1>search :""</h1>");
			var a=document.getElementById("but1");
			window.location.href=(" Test succeeded ");
		<input type="button" name="" id="but1" value="test window.location.href" />

(7)Window History --- historical object


                             1. window. The history object contains the history information of the browser.

                             2.history.back() - the same as clicking the back button in the browser

                             3.history.forward() - the same as clicking the button forward in the browser

                             4.history.go(-/+number) - load a specific page in the history list.

Example: the following line of code performs the same operation as clicking the back button twice: history go(-2)


1. First page: function. You can jump to the second page and advance to the third page

<!DOCTYPE html>
		<meta charset="utf-8">
		<script type="text/javascript">
				function toNext(){
		function toNext3(){
		function togo(){
		<h4>History Object properties
 attribute	describe
length	Return to the browser history list URL quantity<br>
History Object method<br>
method	describe<br>
back()	load history Previous in list URL. <br>
forward()	load history Next in the list URL. <br>
go()	load history A specific page in the list.</h1>
<h4>History Object description
History Object was originally designed to represent the browsing history of the window. But for privacy reasons, History Object no longer allows scripts to access actual objects that have been accessed URL. <br>The only function that remains in use is back(),forward() and go() method.
The following line of code performs the same operation as clicking the back button:<br>
The following line of code performs the same action as clicking the back button twice:<br>
		<h1>First test page</h1>
		<a href="test.html">Connect to the second test page</a><br>
		<input onclick="toNext()" type="button" name="" id="but1" value="forward" />
		<input onclick="toNext3()" type="button" name="" id="but2" value="Forward 3" />
		<input onclick="togo()" type="button" name="" id="but3" value="go3" />

2. Page 2 function: it can advance to the next page or back to the previous page

<!DOCTYPE html>
		<meta charset="utf-8">
		<script type="text/javascript">
				function toNext(){
			function toBack(){
		<h1>2nd test page</h1>
		<a href="test2.html">Connect to the third test page</a><br>
		<input onclick="toNext()" type="button" name="" id="but1" value="forward" />
		<input onclick="toBack()" type="button" name="" id="but2" value="back off" />

3. Page 3, function: you can go back to the previous page or return to the home page

<!DOCTYPE html>
		<meta charset="utf-8">
		<script type="text/javascript">
			function toBack1(){
			function togo(){
				var a=window.history.length;
		<h1>Third test page</h1>
		<input onclick="toBack1()"  type="button" name="" id="but2" value="back off" />
			<input onclick="togo()"  type="button" name="" id="but3" value="Return to the home page after" />

Note: forward history Forward () and backward history Back() is only valid for pages in the same window.

(8).Window Navigator -- browser information

 window. The Navigator object contains information about the visitor's browser.

<!DOCTYPE html>
		<meta charset="utf-8">
		document.write("<h1>Browser code:"+window.navigator.appCodeName+"</h1>");
		document.write("<h1>Browser name:"+window.navigator.appName+"</h1>");
		document.write("<h1>Browser version:"+window.navigator.appVersion+"</h1>");
		document.write("<h1>Enable Cookies:"+window.navigator.cookieEnabled+"</h1>");
		document.write("<h1>hardware platform :"+window.navigator.platform+"</h1>");
		document.write("<h1>user agent :"+window.navigator.userAgent+"</h1>");
		document.write("<h1>User agent language:"+window.navigator.systemLanguage+"</h1>");

(9)JavaScript timing event

By using JavaScript, we have the ability to execute code after a set time interval, rather than immediately after the function is called. We call it a timed event.

It is easy to use timed events in JavaScritp. Two key methods are:

setInterval() - executes the specified code continuously for the specified number of milliseconds.

setTimeout() - pauses the specified number of milliseconds before executing the specified code

setInterval() and setTimeout() are two methods of HTML DOM Window objects. Is a global method;

1.setInterval() method



Executes the specified code continuously for the specified number of milliseconds at the specified interval.

Parameter 1 - the running code specified is a function

Parameter 2 - number of milliseconds specified

The setInterval() method keeps calling the function until clearInterval() is called or the window is closed.

The ID value returned by setInterval() can be used as an argument to the clearInterval() method.

The clearInterval(intervalVariable) method is used to stop the function code executed by the setInterval() method.

Parameter intervalVariable --- return value of setInterval()

<!DOCTYPE html>
 		<meta charset="utf-8" />
 		<meta name="viewport" content="width=device-width, initial-scale=1">
		<script type="text/javascript">
			var mysetinterval;
			function testsetInterval(){
				  var hobj =document.getElementById("h1");
				function times(){
				var date=new Date();
				var year=date.getFullYear();
				var month=date.getMonth()+1;
				var dateri=date.getDate();
				var house=date.getHours();
				var minutes=date.getMinutes();
				var seconds=date.getSeconds();
				var time=year+"year"+month+"month"+dateri+"day"+house+"Time"+minutes+"branch"+seconds+"second"
				 hobj.innerHTML=new String(time);
			function stop(){
		<h1 id="h1"></h1>
 		<input type="button" name="" id="" onclick="testsetInterval()" value="time" />
		<input type="button" name="" id="" value="stop it" onclick="stop()" />

  2.setTimeout() method

Executes the specified code after pausing the specified number of milliseconds

Syntax: setTimeout(code,millisec)
setTimeout() executes code only once. If you want to call multiple times,
Please use setInterval() or let code itself call setTimeout() again.

Parameter code -- specifies the code to run; parameter millisec -- specifies the number of milliseconds

To stop the setTimeout() method while it is in progress, also use the clearInterval(intervalVariable) method

The ID value returned by setTimeout() can be used as an argument to the clearInterval() method.

		<script type="text/javascript">
			var stop;
			function timeout() {
				var t = setTimeout("alert('3 seconds!')", 3000);
				stop = t;
			function stoptimeout() {
		<input type="button" value="test settimeout" onClick="timeout()">
		<input type="button" value="Test stop settimeout" onClick="stoptimeout()">

Tags: Javascript

Posted by cmgmyr on Wed, 04 May 2022 21:33:17 +0300