JS introductory notes

Original link: https://yzyyz.top/archives/start_with_JS.html

v2-25182ac6197d798d6d8b22d3b0710cbf_1440

Introductory stuff, nothing fancy

variable

var

var declares a variable with global or function level scope

 1
2
3
4
5
6
7
8
9
10
 var a;
var b = "123" ;
var c = 0 , d = 1 ;

// destruct
var li = [ 1 , 2 , 3 , 4 ];
var [n1,n2,n3,n4,n5] = li;
console.log (n1,n2,n3,n4,n5);

>>> 1 2 3 4 undefined

let

let declares a block-scoped variable

 1
 // declare the same as var

Variables declared in block-level scope cannot be accessed outside

 1
2
3
4
5
6
 {
let a = 123 ;
}
console .log(a) //error

>>> Uncaught ReferenceError : f is not defined

Can’t reset with let in the same scope

 1
2
3
4
 let a = 1 ;
let a = 2 ; //invalid

>>> Uncaught SyntaxError : Identifier 'a' has already been declared

const

const declares one or more constants at the block-level scope, which must be initialized when declaring, and the value cannot be modified after initialization, and the variable cannot be reset like let

 1
2
 const a = 666 ;
const a = 777 ; //Error

But in fact, the object declared by const can be modified

 1
2
3
4
 const a = [ 1 , 2 , 3 ]
a[ 0 ] = 0 ;
console.log (a)
>>> [ 0 , 2 , 3 ]

variable promotion

Both function and variable declarations will be hoisted to the front of the function

 1
2
3
 a = 0 ;
console.log (a);
var a;

Functions created in the form of function declarations will be created before execution

function expressions are not advanced

 1
2
3
4
5
6
7
8
9
10
11
 fun();
function fun ( ) {
console.log ( 666 );
}
>>> 666

fun2();
var fun2 = function ( ) {
console.log ( 777 );
}
>>>Uncaught TypeError : fun2 is not a function

type of data

typeof is used to check the type

String

Number

 1
2
3
4
 console .log( Number .MAX_VALUE) // The maximum value that js can represent, if it is greater than it returns Infinity
>>> 1.7976931348623157e+308
console .log( Number .MIN_VALUE) // The smallest positive value that js can represent
5e-324

Infinity is infinity

-Infinity negative infinity

NaN not a number

Floating-point arithmetic results may be imprecise

Boolean

Null

null empty object

Undefined

undefined undefined

Object

type conversion

 1
2
3
4
5
6
 var a = 123 ;
a = a.toString(); // null and undefined do not have this method

a = String (a);

a = a + "" ;
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 var a = "123" ;
a = Number (a); // 123

var b = "12abc" ;
b = Number (b); // NaN

var c = null ;
c = Number (c); // 0


var a = "100px"
var b = parseInt (a) // 100

var a = "0.5em"
var b = parseFloat (b) // 0.5

0 , NaN , "" , null , undefined are converted to false

 1
2
3
 var a = 0 ;
a = Boolean (a); // false
a = !!a // convert it to boolean using two NOT operations

other

Hexadecimal: 0x10

Octal: 010, some browsers treat it as decimal

Binary: 0b10, poor compatibility

Unicode: \u100 (Use ⚀ in web pages)

0e2396c4j00r3be2k003yc000u0019dm.jpg&thu

operator

arithmetic operators

+ - * / %

unary operator

-a +a

self-increment

a++ original value, ++a new value

Logical Operators

No

 1
2
 var a = true ;
a = !a; // false

&& with

|| or

assignment operator

a += 1; …

relational operator

Comparing string numbers must be converted

equality operator

== ===

conditional operator

条件表达式?语句1:语句2;

true executes 1, false executes 2

operator precedence

Loop judgment

if

 1
2
3
4
5
 if (){
...;
} else if (){
...;
}

switch

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 if (a == 1 ){
...;
} else if (a == 2 ){
...;
}


switch (a == 1 ){
case 1 :
...;
case 2 :
...;
default :
...;
break ;

}

while

 1
2
3
4
5
6
7
8
 while (){

}

// infinite loop
while ( true ){

}

for

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
 for ( var a= 1 ; a< 10 ; a++){
...;
}

// infinite loop
for (;;){

}

// label
name_test:
for (;;){
break name_test;
}

Object

built-in objects

Objects defined by the ES standard

function Math String …….

host object

Browser-provided objects

Objects in BOM and DOM

window

Common properties
  • document

    document object

  • console

  • location

    Address object, read web links or control jumps

  • localStorage

    local storage

  • screen

    get screen resolution

  • scrollX, scrollY

    X, Y scroll bar position

Common method

  • alert

  • confirm

  • blur

    Move focus out of current window

  • close

    close the window

  • eval

    Execute a js statement in the form of a string

  • focus

    Activate the current window

  • open

    Open new window (tab)

  • openDialog

    Open new dialog window

  • print

    Dialog box showing print function

  • prompt

    Pop up the input box (will block js)

  • scroll

    Control the scroll bar to the specified position

  • stop

    stop loading

custom object

 1
2
3
4
5
6
7
8
9
10
11
 // The new keyword calls the constructor constructor
var obj = new Object ();
obj.name = "Xiao Zhuang" ;
console.log( obj.name );

delete obj.name; //delete

obj[ "123" ] = 456 ; //This formal definition should be taken in the same way
console.log (obj[ "123" ]);

console .log( "age" in obj); //check, return boolean

obj.png

 1
2
3
4
5
6
7
8
 // object literal

var a = {};
var b = {
name: "Xiao Zhuang" ,
age: 19 ,
skills:{ shoot : 100 ;}
};

function

function

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 var fun = new Function ( "console.log('6666')" ) // not commonly used

function func_name ( a,b ) {
return a+b;
}

// anonymous function
var fun1 = function ( ) {
...;
}

// execute immediately
( function ( ) {
return ;
})()

method

 1
2
3
4
5
6
7
8
9
10
11
 var fun = function ( ) {
return ;
}
fun() // call function

var b = {
say: function ( ) {
alert( "hi" );
}
}
b.() // call method

scope

global scope

The code written directly in js is created when the page is opened and destroyed when it is closed;

There is an object window in the global scope, and the created variables are saved as properties of window ; the created functions are saved as methods of window ;

Variables in the global scope are global variables

 1
2
3
4
5
6
7
8
 var a = 123 ;
function fun ( ) {
console.log ( "6" );
}
console.log ( window.a )
window.fun ()
>>> 123
>>> 6

function scope

Created when the function is called, destroyed after execution, and created for each call, independent of each other;

Variables in the global scope cannot be accessed;

When manipulating a variable in the function scope, first look for it in its own scope, if not, look for the upper level, until the global scope, if not found, a ReferenceError

Implicit parameter

this

An implicit parameter passed by the parser to the internal when calling a function, this points to different objects according to the method of the function call;

  • Call it in the form of a function that points to window

  • Called as a method, it points to the object

  • Called as a constructor, pointing to the newly created object

  • When using call() and apply() , point to the specified object

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
 function fun ( ) {
console.log ( this );
}

var obj={
name: "Xiao Zhuang" ,
say: fun
};
fun();
obj.say()

>>>Window { window : Window, self : Window, document : document , name : '' , location : Location, …}

>>>{ name : 'Xiao Zhuang' , say : ƒ}

call() and apply()

Both call() and apply() are methods of function objects, and functions are executed when called.

When calling, you can specify an object as the first parameter, and the object will become this when the function is executed.

 1
2
3
4
5
6
 var a = { name : "Apricot Flower" };
function fun ( ) {
console.log ( this.name );
}
fun.call(a);
>>> Apricot Blossom

call() and apply() pass parameters differently

 1
2
3
4
5
6
7
8
9
10
 function fun ( a,b ) {
console .log( this .name+a+ "," +b);
}
obj = { name : "Apricot Blossom" };

fun.call(obj, 1 , 2 ); // pass in turn
fun.apply(obj,[ 1 , 2 ]) // encapsulate passed as an array

>>> apricot flower 1 , 2
>>> apricot flower 1 , 2

arguments

It is also an implicit parameter passed in, which is an array-like object

  • The arguments passed by the calling function are stored in arguments , arguments.length can be used to get the length of the arguments
  • Even if you don’t define formal parameters, you can use it to get
 1
2
3
4
5
 function fun ( ) {
console.log ( arguments [ 0 ]);
}
fun( "haha" , 123 );
>>> haha
  • arguments have a callee property, which is the currently executing function
 1
2
3
4
5
6
7
8
 function fun ( ) {
console .log( arguments .callee );
}
fun( "haha" , 123 );

>>>ƒ fun(){
console .log( arguments .callee );
}

factory function

 1
2
3
4
5
6
7
 function createSth ( name ) {
var obj = new Object ();
obj.name = name;
return obj;
}

var o = createSth( "Xiao Zhuang" );

Constructor

The constructor is created with the new keyword

  • will immediately create a new object

  • Set the newly created object as this in the function

  • execute code

  • return object

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 function Preson ( name ) {
this .name = "Ding"
console.log ( this.name )
}
var p = new Person();


function Plants ( name ) {
this .name = "plant" ;
console.log ( this.name )
}
var p2 = new Plants();


// instanceof checks if an object is an instance of a class, note that all objects are descendants of `Object`
console .log(p2 instanceof Person);
>>> false

Look at the code below

 1
2
3
4
5
6
7
8
9
10
 function Person ( name ) {
this.name = name;
this .run = function ( ) {
console .log( this .name+ "moistened" );
}
}
var p1 = Perso( "a" );
var p2 = Person( "b" );
console.log( p1.run == p2.run)
>>> false

If you construct n objects with this constructor, n new run methods are created, which is unnecessary:

 1
2
3
4
5
6
7
8
9
10
11
12
13
 function Person ( name ) {
this.name = name;
this.run = run;
}

function ( ) run ( ) {
console .log( this .name+ "moistened" );
}

var p1 = Perso( "a" );
var p2 = Person( "b" );
console.log( p1.run == p2.run)
>>> true

However, the above definition of functions in the global scope will pollute the namespace of the global scope, and it is not safe. This means the prototype object

prototype object prototype

For each function created, the parser adds a prototype property to it, accessed via __proto__

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 function MyClass ( ) {

}
MyClass.prototype.a = 123 ;

var mc = new MyClass();
var mc2 = new MyClass();
var mc3 = new MyClass();

console .log(mc.a) // mc.__proto__.a
>>> 123


// Check if there is a property in mc, if you don't have it yourself, if the prototype has it, it will also return true
console .log(a in mc) // true

// At this point, you can use hasOwnProperty() to check if the object itself has
console .log(mc.hasOwnProperty( "a" )) // false

proto.png

The prototype of an Object object has no prototype

toString()

When console.log() prints an object, it actually outputs the return value of the object’s toString()

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 function P ( ) {
this .name = "A"
}
var a = new P();

console .log(a); // [object Object]
console .log(a.toString()); // [object Object]
// but I display them differently on edge


p.prototype.toString = function ( ) {
console.log ( "666" );
}

console .log(a); // [object Object]
console .log(a.toString()); // [object Object]

garbage collection

When an object does not have any variable or property reference to it, it can never be manipulated at this time, it is garbage;

JS has an automatic garbage collection mechanism that will automatically destroy it, we just need to set its reference to null

arrayArray

 1
2
3
4
5
6
7
 var arr = new Array ();
var arr1 = new Array ( 3 );
var arr2 = [];
arr[ 0 ]= 1 ;
console.log( arr1.length ) //3
arr2.length = 4
console.log( arr2.length ) //4

Methods JavaScript Array Reference Manual (w3school.com.cn)

timeDate

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
twenty one
twenty two
twenty three
twenty four
 var d = new Date (); // Created directly with the constructor, it will encapsulate the current code execution time
console.log (d);

>>> Wed Aug 17 2022 06 : 26 : 05 GMT+ 0800 (China Standard Time)


// build the specified object
var d2 = new Date ( "08/08/2021 12:00:30" );

// day
var d3 = d2.getDate();

// Day of the week (0 is Sunday)
var day = d2.getDay();

// month (0 is January)
var month = d2.getMonth();

// year (4 digits)
var year = d2.getFullYear();
...

// timestamp (1970/1/1 00:00:00)
var time = d2.getTime();

JavaScript Date Reference Manual (w3school.com.cn)

Math

It is not a constructor, it belongs to a utility class, no need to create

 1
2
 console.log ( Math.PI );
>>> 3.141592653589793

JavaScript Math Reference Manual (w3school.com.cn)

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 console .log( Math .ceil( 1.4 )); // round up
>>> 2

console .log( Math .floor( 1.4 )); // round down
>>> 1

console .log( Math .round( 1.4 )) // round up
>>> 1

console .log( Math .random()); // 0-1 random number

// random number between 0-x
var x = 10 ;
console .log( Math .round( Math .random()*x));
>>> 8

// Generate random numbers for xy
console .log( Math .round( Math .random()*(yx))+x);

Packaging class

Three wrapper classes are provided in JS, through which basic data types can be converted to objects:

  • String()
  • Number()
  • Boolean()
 1
2
3
4
5
6
 var num = new Number ( 1 );
console.log ( typeof num);
>>> object

var num2 = new Number ( 1 );
console .log(num == num2); // false

There is basically no packaging class in development

When properties and methods are called on values ​​of primitive data types, the browser temporarily uses the wrapper class to convert them to objects before calling the properties and methods

After calling, convert to basic data type

 1
2
3
4
 var a = 132 ;
a = a.toString();
console.log (a);
>>> 123

String String

some methods

Store the underlying string as an array [“H”, “e”, ….]

JavaScript String Reference Manual (w3school.com.cn)

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
twenty one
twenty two
twenty three
twenty four
 var str = "Hello YZYYZ" ;
console .log(str.length); // spaces are counted
>>> 11

var a = str. charAt( 0 ); // H

var a = str.charCodeAt( 0 ); // 72 (Unicode character code)

var a = String .formCharCOde( 72 ); // H

var str.concat( "haha" ); // str + "haha"

var a = str.indexOf( "H" ); // 0 finds the index of the first occurrence of the specified character, does not return -1

lastIndexOf() // back to front

var a = str.slice( 0 , 5 ); // Hello intercepts the second parameter of the ancestor string and can be omitted

var a = str.subString( 1 ); // same as slice, but the parameter cannot accept negative numbers, if the second parameter is less than the second, the parameter position will be automatically swapped

var a = str.split( " " ) // split into an array

var a = str.toUperCase() // convert case
var a = str.toLowerCase()

regular expression

 1
2
3
4
5
6
7
 var re = new RegExp ( "a" );
var str = 'abc' ;
console .log(re.test(tel)); // true

var re = /^1[3-9]\d{9}$/ ;
var tel = "13009985544" ;
console .log(re.test(tel)) // true

Methods that support regular String objects

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 var str = "123qqq345www456eee567ABCDEFG" ;
var re = /[az]+/ig ;

var result = str.search(re);
console .log(result); // returns the index of the first occurrence
>>> 3

result = str.match(re);
console.log (result);
>>> [ 'qqq' , 'www' , 'eee' , 'ABCDEFG' ]

result = str.replace(re, "*" );
console.log (result);
>>> 123 * 345 * 456 * 567 *

result = str.split(re);
console.log (result);
>>> [ '123' , '345' , '456' , '567' , '' ]

DOM

Document Object Model

JS operates on HTML documents through DOM

  • Documentation: HTML web page
  • Objects: each part of the web page becomes an object
  • Model: Represents the relationship between objects

Node Node

A node is the most basic part of a web page, and each part of a web page can be called a node

nodeName nodeType nodeValue
document node #document 9 null
element node label name 1 null
property node property name 2 attribute value
text node #text 3 text content

The browser provides the document node object, which is the window property and can be used directly on the page

 1
2
3
4
5
6
 ...
< button id = "btn" > click me </ button >
< script type = "text/javascript" >
console .log( document .getElementById( "btn" ).innerHTML)
</ script >
...

event

HTML DOM Events (w3school.com.cn)

  • addEventListener Add event listener
  • dispatchEvent triggers the specified event manually
  • getAttribute Gets the specified attribute of the label
 1
2
3
4
5
 function fun ( ) {
alert( "haha" );
}
var btn = document .getElementById( "btn" );
btn.onclick = fun

document loading

 1
2
3
4
5
6
7
8
9
10
11
12
13
 ...

< script type = "text/javascript" >
window.onload (){
btn = document .getElementById( "btn" );
btn.onclick = function () {
alert(btn.innerHTML)
}
}
</ script >

< button id = "btn" > click me </ button >
...

DOM query

get element node

  • getElementById()
  • getElementsByTagName()
  • getElementsByName()

get child node

  • childNodes

    Text properties are also treated as nodes

  • children

    recommend

  • firstChild

  • firstElementChild

    The first child element is IE dead, but it is only compatible with IE9+

  • lastChild

Get parent and sibling nodes

  • parentNode

    parent node

  • previousSibling

    previous sibling

  • nextSibling

According to class

  • getElementsByClassName

    Include all elements of itself

Selector

  • document.querySelector()

    only find the first

  • document.querySelectorAll()

    return array

DOM additions, deletions and modifications

HTML DOM Element Object (w3school.com.cn)

  • document.createElement()

    Takes a tag name as a parameter and returns this object

  • document.createTextNode()

    Create a text node, the parameter is text, and return the node

  • appendChild()

    parent element. appendChild(child element)

  • insertBefore()

    parent node.insertBefore(new node, old node)

  • replaceChild()
    replaceChild(new node, old node)

  • removeChild()
    parent node. removeChild(child node)
    parent node: child node. parentNode

This article is reprinted from: https://yzyyz.top/archives/start_with_JS.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment