Front-end learning JavaScript

1. The maximum value of a number that can be represented in JS and the minimum value greater than zero

  • Number.MAX_VALUE和Number.MIN_VALUE
  • If it is greater than Number.MAX_VALUE, use Infinity (positive infinity) to express it, and -Infinity to express it (negative infinity).
  • NAN is a special number that means Not A Number
  • Use typeof to check Number.MAX_VALUE, NaN and Infinity to get the result number
  • Try not to use JS to calculate floating point numbers, especially when accuracy requirements are high. For details, see
    why 0.1+0.2 === 0.3 is false in JavaScript.

2. Forced type conversion

1. The difference between String() and toString():

Usage of toString():

let a = 123;
a.toString()

toString() cannot convert variables with null and undefined values ​​into strings.
Usage of String():

let a = 123;
String(a)

String() can turn null and undefined variables into strings

2. The difference between Number(), parseInt() and parseFloat():

Number:
1. If it is a purely numeric string, it can be converted directly to a number
2. If it has a non-numeric string, it is converted to NaN
3. If it is an empty string or all spaces, it is converted to 0
4 .If the boolean value is true, it is converted to 1, if it is false, it is converted to 0
5. If the value is null, it is converted to 0
6. If the value is undefined, it is converted to NaN

parseInt:
You can take out the valid integer starting from the first character in a string

let a = '123px';
a = parseInt(a);   //a = 123
let b = '123.456px';
b = parseInt(b);   //b = 123
let c = '123b456px';
c = parseInt(c);   //c = 123
let d = 'b123px';
d = parseInt(d);   //d = NaN

parseFloat:
You can take out the valid floating point numbers starting from the first character in a string.

let a = '123.456px';
a = parseFloat(a);   //a = 123.456
let b = '123.456.789px';
b = parseFloat(b);   //b = 123.456
let c = '123.456b456px';
c = parseFloat(c);   //c = 123.456
let d = 'b123.456px';
d = parseFloat(d);   //d = NaN
let e = '123px';
e = parseFloat(e);   //e = 123

If you use parseInt and parseFloat for non-String type variables, the method will first convert the variable to String type, and then operate

let a = true;
a = parseFloat(a);   //a = NaN
a = parseInt(a);     //a = NaN
let b = null;
a = parseFloat(b);   //a = NaN
a = parseInt(b);     //a = NaN
let c = undefined;
a = parseFloat(c);   //a = NaN
a = parseInt(c);     //a = NaN
let d = 198.123;
d = parseInt(d);     //d = 198   可以用来给浮点数取整
let e = 070;         //0开头代表八进制的数字,0x开头代表十六进制的数字
e = parseInt(e, 10); //e = 56 第二个参数指定数字的进制
3.Boolean()
  1. Number----->Boolean
    Except for 0 and NaN, everything else is true

  2. String----->Boolean
    Except for the empty string, everything else is true

  3. Both null and undefined are converted to false

  4. Object will also be converted to true

  5. if() will implicitly convert the judgment condition in the parentheses to a Boolean type, which has the same effect as Boolean()

3. Basic operators

  1. Adding any value to a string will convert the string and perform a string concatenation operation. We can take advantage of this feature to convert any data type into a string, just add an empty string "";
let a = 123;
a = a + "";
console.log(typeof(a));   // string
let resultOne = 1 + 2 + "3";   //ruseltOne = "33"
let resultTwo = "1" +2 + 3;    //reseltTwo = "123"
  1. Any value will be automatically converted to Number when doing - * / operation
  2. For non-Number type values, you can use + to convert them to numbers
let a = "123";
a = +a;     //a = 123(number类型)
let result = 1 + +'2' + 3;    //result = 6
  1. Self-increment (++) and self-decrement (- -)
  • Increment (++):

Through auto-increment, a variable can be increased by 1 based on itself.

After a variable is incremented, the value of the original variable will immediately increase by 1.

There are two types of auto-increment: back++(a++) and front++(++a)

Whether it is a++ or ++a, the value of the original variable will be increased by 1 immediately.

The difference is that the values ​​of a++ and ++a are different

The value of a++ is equal to the original value (the value before the self-increment)
The value of ++a is equal to the new value (the value after the self-increment)

let a = 10;
let resultOne = a++ + ++a + a;    //resultOne = 10 + 12 + 12 = 34
a = a++;     //a = 10
  • Decrement (–):

By decrementing, a variable can be reduced by 1 based on itself.

Auto-decrement is divided into two types: back- -(a- -) and front- -(- -a)

Whether it is a- - or - -a, the value of the original variable will be decremented by 1 immediately.

The difference is that a- - and - -a have different values

a- -The value is equal to the original value (the value before self-decrement)
- -The value of a is equal to the new value (the value after self-decrement)

  1. Relational operators (less than, greater than, less than or equal to, greater than or equal to, equal to, not equal to)
  • When comparing two strings, the encoding of the characters is compared, and only the first one is compared. If the first one is the same, the second one is compared, and so on.
  • Because English comparison is also done through coding, it can be used for sorting.
  • A comparison between a number and a non-numeric value will be converted into a number for comparison. Any comparison with NaN will be false.
  • If a string number is compared with a number type number, it will be automatically transformed, but comparing the numbers of two strings will have unpredictable results.
  1. Encoding
    Here we say UTF-8, also known as Universal Code. Each text or letter is represented by four hexadecimal digits.
    If we want to use some uncommon symbols, we can use \u+ to display the symbol encoding.
console.log('\u2620')

Insert image description here

  1. equality operator
  • undefined == null
console.log(undefined == null) // true
  • NaN is not equal to any value, including itself
console.log(NaN == NaN) // false
  • The difference between the === equality operator and the == equality operator:
    the equality operator will automatically perform type conversion, but the equality operator will not
console.log(undefined == null) // true
console.log(undefined === null) // false
  • The difference between !== inequality operator and != inequality operator:
    inequality operator will automatically perform type conversion, while inequality operator will not
console.log(1 != '1') // false
console.log(1 !== '1') // true
  1. conditional operator

Conditional operator is also called ternary operator

Syntax:
Conditional expression?Statement 1:Statement 2;

Execution process:
When the conditional operator is executed, it first evaluates the conditional expression.
If the value is true, statement 1 is executed and the execution result is returned . If the value is false, statement 2 is executed and execution is returned. result

4. Cycle

  1. The function of break:
  • break is used to exit switch and loop statements
  • break only interrupts the most recent loop statement
for(var i=0;i<5;i++){
    
    
	console.log("外层循环:"+i);
	for(var j=0;j<5;j++){
    
    
		break;
		console.log("内层循环:"+j);
	}
}

Insert image description here

  • break can interrupt the loop with the specified name
outer: /*outer是第一个for循环的名称*/
for(var i=0;i<5;i++){
    
    
	console.log("外层循环:"+i);
	for(var j=0;j<5;j++){
    
    
		break outer;
		console.log("内层循环:"+j);
	}
}

Insert image description here

  1. The role of continue:
  • continue is used to skip the current loop
for(var i = 0;i<5;i++){
    
    
	if(i == 2){
    
    
		continue;
	}
	console.log(i);
}

Insert image description here

  • continue only interrupts the most recent loop statement
  • continue can interrupt the loop with the specified name
  1. Prompt loop efficiency through break
//测试如下的程序的性能
//在程序执行前,开启计时器
//console.time( "计时器的名字")可以用来开启一个计时器
//它需要一个字符串作为参数,这个字符串将会作为计时器的标识
console.time( "test" );
//打印2-10000之间所有的质数
for(var i = 2;i<10000;i++){
    
    
	var flag = true;
	for(var j = 2;j<i;j++){
    
    
		if(i%j ==0){
    
    
			//如果进入判断则证明 i不是质数,修改flag值为false
			flag = false;
			//一旦进入判断,则证明 i不可能是质数了,此时循环再执行已经没有任何意义了
			//使用break来结束循环
			break;
		}
	}
	//如果是质数,则打印 i的值
	if(flag){
    
    
		//console.log(i); //为了测试使用和不使用break的性能,去掉输出,减少输出时间,减少误差
	}
}
// console.timend()用来停止一个计时器,需要一个计时器的名字作为参数
console.timeEnd( "test" );

Use break:
Insert image description here
Do not use break:
Insert image description here

5. Object

1.Data types in JS:
  • String string
  • Number value
  • Boolean
  • Null null value
  • UndefinedUndefined

The above five types are basic data types. The values ​​we see in the future, as long as they are not the above five types, are all objects.

object object

If we use basic data types, the variables we create are independent and cannot be integrated into a whole.

Objects belong to a composite data type, and attributes of multiple different data types can be stored in the object.

Classification of objects:

  1. Built-in objects
    are objects defined in the ES standard and can be used in any ES implementation.
    For example: Math String Number Boolean Function 0object... . .

  2. Host objects
    are objects provided by the JS running environment. Currently, they mainly refer to objects provided by the browser,
    such as BOM DOM.
    The console in console.log() is an object.
    The document in document.write() is also an object.

  3. Custom object
    An object created by the developer himself

2. Operation object
  1. Create an object.
    The function called using the new keyword is the constructor. The constructor
    is a function specially used to create objects.
var obj = new Object();
//使用typeof检查一个对象时,会返回object
console.log(typeof obj)
  1. Adding attributes
    The values ​​saved in the object are called attributes.
    Adding attributes to the object
    syntax: object.attribute name = attribute value
//向obj中添加一个 name属性
obj.name ="猪八戒";
//向obj中添加一个 gender属性
obj.gender ="男";
//向obj中添加一个 age属性
obj.age = 18;
  1. Syntax for reading properties in an object
    : object.property name
console.log(obj.name);// 猪八戒

If you read a property that is not in the object, no error will be reported, but undefined will be returned.

  1. Modify the attribute syntax in the object
    : object.property name = new value
obj.name = "沙和尚"
  1. Delete attributes in the object
    Syntax: delete object.attribute name
delete obj.name;
3.Attribute name and attribute value
  1. Attribute name
    In addition to adding attributes to the object through object. Attribute name = attribute value , you can also add attributes to the object through another method:
    syntax: object ["attribute name"] = attribute value.
    The attribute name written in this way can be any character. Composition, can even be a variable
var obj = new Object();
obj["123"] = 789;
obj["wenhao"] = "你好呀!";
var n = "wenhao"; // 让变量n等于属性名
console.log(obj["123"]); // 789
console.log(obj[n]); // 通过读取变量n得到属性名“wenhao”,从而得到属性值“你好呀!”
  1. Property value
    The property value of a JS object can be any data type, or even an object.
var obj = new Object();
obj.test = null;
obj.test = undefined;
var obj2 = new Object();
obj2.name = "宋江";
obj.test2 = obj2;
console.log(obj.test2);
console.log(obj.test2.name); // 读取ogj2中的属性

Insert image description here

4. Basic data types and reference data types

Variable b is equal to variable a. If the value of a is changed, the value of b will not change.

var a = 123;
var b = a;
a++
console.log(a); // 124
console.log(b); // 123

Reason:
Variables in JS are saved in stack memory. Values ​​of basic data types are stored directly in stack memory. Values ​​exist independently. Modifying one variable will not affect other variable objects. Obj2 is equal to obj

Insert image description here
. If you change the name of obj, the name of obj2 will also change accordingly.

var obj = new Object();
obj.name = 'swk';
var obj2 = obj;
obj.name = 'zbj';
console.log(obj.name);  // zbj
console.log(obj2.name); //zbj

Reason:
The object is saved in the heap memory. Every time a new object is created, a new space will be opened up in the heap memory, and the variable saves the memory address of the object (reference of the object). If two variables What is saved is the same object reference. When one modifies a property through a variable, the other will also be affected.

Insert image description here
Object obj2 is equal to obj. Let obj2 be equal to null. Obj does not become null.

var obj = new Object();
obj.name = 'swk';
var obj2 = obj;
obj2 = null;
console.log(obj);  // Object
console.log(obj2); //null

Reason: obj2=null means that its pointer is null. At this time, it no longer refers to the same address as obj
Insert image description here
. Obj3.name and obj4.name are both 'shs', but they are not equal.

var obj3 = new Object();
var obj4 = new Object();
obj3.name = 'shs';
obj4.name = 'shs';
console.log(obj3.name == obj4.name); // false

Reason:
When comparing values ​​of two basic data types, you are comparing values.
When comparing two reference data types, it is the memory address of the compared object.
If the two objects are exactly the same but have different addresses, it will also return false.

Insert image description here

5. Object literals

The second method of creating a new object:

var obj = {
    
    };

advantage:

  1. More convenient and concise
  2. When creating an object, you can directly specify the attribute name and attribute value.
var obj = {
    
    
	name:'swk',
	age:24
}
6. Built-in objects
(1).Array

Arrays are also objects.
Arrays have similar functions to our ordinary objects. They are also used to store some values. The difference is that ordinary objects use strings as attribute names, while arrays use numbers as indexes to operate element indexes: integers starting from
0 are index.
Why use arrays?
The storage performance of arrays is better than that of ordinary objects . In development, we often use arrays to store some data.

var arr = new Array(); // 创建一个数组对象
var arr2 = []; // 使用字面量创建一个数组对象
console.log(arr); // []
console.log(typeof arr); // object

Add elements to an array
Syntax: array name [index] = value

arr[0] = 10; // 向数组中索引为0的地方添加值10
arr[1] = 20;
console.log(arr[3]); // 读取不存在的索引,不会报错,会返回undefined

You can use the length attribute to get the length of the array (number of elements)
Syntax: array.length

arr[0] = 10; 
arr[1] = 20;
console.log(arr.length); //2
console.log(arr); // [10, 20]
arr[10] = 20;
console.log(arr.length); //11
console.log(arr); // [10, 20, , , , , , , ,20]未赋值的地方默认为空

For a continuous array, use length to get the length of the array (the number of elements). For a non-continuous array, use length to get the maximum index + 1 of the array.

Modify length

arr[0] = 10; 
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr.length = 10 // 设置长度为10
console.log(arr); // [10, 20, 30, 40, , , , , ,]
arr.length = 2 // 设置长度为2
console.log(arr); // [10,20] 后面的值被截断了

The elements in the array can be of any type

var arr = ['Hello',true,123,null,undefined];
console.log(arr);

Can put objects

var obj = {
    
    name:'swk'}
var arr = [obj];
console.log(arr);
console.log(arr[0].name);

You can put functions

var arr = [function fun(){
    
    console.log('我是一个函数')}];
console.log(arr);
console.log(arr[0]());

Arrays can be placed

var arr = [[1,2,3],[4,5,6]];
console.log(arr);

Array methods:

  • pop: can delete the last element of the array and return the element as the return value
  • push: Insert one or more elements to the end of the array and return the new length of the array as the return value
  • unshift: Insert one or more elements to the beginning of the array and return the new length of the array as the return value
  • shift: You can delete the first element of the array and return the element as the return value
  • forEach()
    forEach() is a callback function.
    Callback function: Created by us, but not called by us, the function forEach() called by the browser itself
    has four parameters:
    the first parameter (value in the example) is
    the second parameter currently being traversed (the value in the example) index), which is the index of the element currently being traversed.
    The third parameter (arr in the example) is the array being traversed.
    The fourth parameter (arr2 in the example), this (represents the object you want to use)
var arr = ['孙悟空','猪八戒','沙和尚','唐僧','牛魔王'];
var arr2 = ['123'];
arr.forEach(function(value,index,arr) {
    
    
	console.log('value = '+value);
	console.log('index= '+index);
	console.log('arr= '+arr);
	console.log('a=',this[0]); // 此时this指向arr2
},arr2)

Insert image description here

  • Slice
    can be used to extract specified elements from an array.
    This method does not change the element array, but encapsulates the intercepted elements into a new array and returns it. Parameters
    :
    1. The index of the starting position of interception, including the start index
    2. The end of interception The index of the position does not include the end index. The second parameter can be omitted.
  • Splice
    using splice() will affect the original array, delete the specified element from the original array,
    and return the deleted element as a return value.
    Parameters:
    1. Indicates the index of the starting position
    2. Indicates the number of deletions
    3 and more Parameters. Represents the replaced elements. These elements will be automatically inserted in front of the starting position index.
  • concat
    is used to connect two or more arrays or elements
var arr = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [7,8,9];
var result = arr.concat(arr2); // 连接两个数组
var result2 = arr.concat(arr2,arr3); // 连接多个数组
var result3 = arr.concat(arr2,arr3,'a','b','c'); // 还能连接多个元素
console.log(result);
console.log(result2);
console.log(result3);
console.log('arr = '+arr+' || arr2 = '+arr2+' || arr3 = '+arr3); //concat不会影响原数组

Insert image description here

  • join
    converts array to string
var arr = [1,2,3];
var result = arr.join(); // 默认使用逗号(,)来作为连接符
var result2 = arr.join('@@@'); // 使用@@@作为连接符,
console.log(result);
console.log(typeof result); // 类型是String
console.log(result2);
console.log('arr = '+arr); // 不会影响原数组

Insert image description here

  • reverse
    flips the array
var arr = [1,2,3,4,5];
var result = arr.reverse();
console.log(result); // 将数组头尾翻转
console.log(arr); // 原数组会被影响

Insert image description here

  • sort Sort
    according to Unicode code
var arr = ['b','d','a','c','f','e'];
var result = arr.sort();
console.log(result); // 根据Unicode重新排序
console.log(arr); // 会影响原数组

Insert image description here

// 要求升序排列
var arr = [5,4,9,2,7,11];
var result = arr.sort();
console.log(result); // 纯数字也会根据Unicode重新排序,但是有两位数和一位数时,只会比较第一位数,会出现问题
var result2 = arr.sort(function(a,b) {
    
     // 可以加一个回调函数,修改sort()比较数字时的bug
	if (a>b) {
    
    
		return 1; // 返回大于0的数,a和b会交换位置
	} else if (a<b) {
    
    
		return -1; // 返回小于0的数,a和b不会交换位置
	} else {
    
    
		return 0; // 返回等于0的数,a和b不会交换位置
	}
	// 更简便的方法
	// return a - b; // 升序排列
	// return b - a; // 降序排列
});
console.log(result2); // 加上回调函数后的结果

Insert image description here

(2). Function methods call() and apply()
  • These two methods are methods of function objects and need to be called through function objects.
  • When call() and apply() are called on a function, the function will be called for execution.
  • When calling call() and apply(), you can specify an object as the first parameter. At this time, this object will become this when the function is executed.
  • The call() method can pass the actual parameters in sequence after the object
  • The apply() method needs to encapsulate the actual parameters into an array and pass them uniformly
function fun(a,b) {
    
    
	console.log('我是fun函数');
	console.log('我的名字是'+this.name);
	console.log('a= '+a+' , b= '+b);  
}
var obj = {
    
    name:'swk'};
var obj2 = {
    
    name:'zbj'};
fun(); // 我是fun函数
fun.call(); // 可以调用fun函数
fun.apply(); // 可以调用fun函数
fun.call(obj,2,3); // this指向obj,2和3是实参
fun.apply(obj2,[4,5]); // this指向obj2,4和5是实参,用数组的形式传入

Insert image description here
This case:

  1. When called as a function, this is always window
  2. When called as a method, this is the object on which the method is called.
  3. When called as a constructor, this is the newly created object
  4. When calling using call() and apply(), this is the specified object
(3).arguments

When calling a function, the browser will pass in two implicit parameters every time:

1. The context object of the function this
2. The object arguments that encapsulates the actual parameters

  • arguments is an array-like object, which can also operate data through indexing and obtain the length.
  • When calling a function, the actual parameters we pass will be saved in arguments.
  • arguments.length can be used to get the length of the actual argument
  • Even if we do not define formal parameters, we can still use actual parameters through arguments.
  • There is an attribute in it called callee. This attribute corresponds to a function object, which is the object of the function currently pointed to.
function fun(){
    
    
	console.log('是否是数组:'+Array.isArray(arguments));
	console.log('实参的长度:'+arguments.length);
	console.log('第一个实参:'+arguments[0]);
	console.log(arguments.callee == fun);
}
fun('Hello',1,2,true);

Insert image description here

(4). Date object

getTime()

  • Get the timestamp of the current date object
  • Timestamp refers to the number of milliseconds it takes from January 1, 1979, Greenwich Mean Time, 0:00:00 to the current date (1 second = 1000 milliseconds)
  • The bottom layer of the computer uses timestamps when saving time.
  • Get the timestamp of the current time:
var time = Date.now();
(5). Math object

The Math object is not a constructor, so there is no need to create a new object when using it. You can directly use its properties and methods to use the
properties of Math:

console.log(Math.PI);

Math method:

  • ceil: round up
  • floor: round down
  • round: rounding to an integer
  • random: can be used to generate a random number from 0 to 1

Generate random numbers for XY
Math.round(Math.random * (yx)+x)

  • max: Get the maximum value among multiple numbers
  • min: Get the minimum value among multiple numbers
  • Math.pow(x,y): Returns x raised to the y power
  • Math.sqrt(x): Returns the value of x after taking the square root
(6).Packaging

JS provides us with three wrapper classes through which basic data types can be converted into objects.

String()

  • Basic data type string can be converted to String object

Number()

  • You can convert numbers of basic data types into Number objects

Boolean()

  • Boolean values ​​of basic data types can be converted to Boolean objects, but note: we will not use objects of basic data types in actual applications.

If you use objects of basic data types, doing some comparisons may bring some unexpected results. Since we don't use them, what is the significance of the existence of wrapper classes?

Methods and properties can only be added to objects, not basic data types.

var a = 123;
a = a.toString(); // 基本类型没有方法和属性,那么是怎么调用toString()的呢?
console.log(a);  // 123
console.log(typeof a);  //String

When we call properties and methods on some basic data type values, the browser will temporarily use a wrapper class to convert it into an object, and then after the object's properties and methods are called, it will be converted into a basic data type.

(7).Regular expression
  • search()
    can search whether the specified content is contained in the string. If the specified content is searched, it will return the index of the first occurrence. If it is not searched, it will return -1.
    It can accept a regular expression as a parameter, and then it will be based on the regular expression. Expression to retrieve string
    search() will only find the first one, even if global matching is set, it is useless
str = 'hello abc hello aec afc';
var result = str.search(/a[bef]c/); // 查找abc或aec或afc
var result2 = str.search(/a[bef]c/g); // g代表全局匹配搜索
console.log(result);  //返回第一个匹配的字符的位置
console.log(result2);  // search()只会查找第一个,即使设置全局匹配也没用
  • match()
    can extract qualified content from a string based on a regular expression. By
    default, our match will only find the first content that meets the requirements, and stop retrieval after finding it.
    We can set the regular expression as Global matching mode, so that all content will be matched.
    match() will encapsulate the matched content into an array and return it, even if only one result is found
str = "1a2b3c4h5e6l7l8B9";
var result = str.match(/[A-z]/); // 查找字母,找到一个后就返回
var result2 = str.match(/[A-z]/g); // g代表全局匹配搜索
console.log(result);  // 不使用g全局匹配搜索只返回一个值
console.log(result2); // 使用全局搜索会返回所有搜索到的值
console.log(Array.isArray(result)); // 判断是否是数组

Insert image description here

  • replace()
    can replace the specified content in the string with new content.
    Parameters:
    1. The content to be replaced can accept a regular expression as a parameter
    . 2. The new content
    will only replace the first one by default.
str = "1a2b3c4h5e6l7l8B9";
var result = str.replace(/[A-z]/,'@-@'); // 将第一个字母替换为@-@
var result2 = str.replace(/[a-z]/ig,'$'); // 将全局字母替换为$
console.log(result);  
console.log(result2); 

Insert image description here

  • split()
    can split a string into an array.
    You can pass a regular expression as a parameter in the method, so that the method will split the string according to the regular expression. Even if this method does not specify a global match, it will split all the strings. point
str = "1a2b3c4h5e6l7l8B9";
var result = str.split(/[A-z]/); // 根据字母拆分
var result2 = str.split(/[a-z]/ig); // g代表全局匹配搜索,i表示忽略大小写,可以两种模式一起用
console.log(result);  // 不使用g全局匹配搜索也会自动全部拆分
console.log(result2); 

Insert image description here

6. Function

1.Create a function
  1. Because functions are also objects, you can use new to create a function object ( but it is not recommended in development, it is troublesome )
var fun  = new Function("console.log('我是new出来的函数对象');");
fun();
  1. function function name ([parameter 1, parameter 2, parameter 3...]) {}
function fun2(){
    
    
	console.log("我是直接创建的函数!");
}
fun2();
  1. Assign an anonymous function to a variable
var fun3 = function(){
    
    
	console.log('我是赋值给变量的匿名函数!');
};
fun3();

Extension:
Immediate execution of function: After the function is defined, it is called immediately. This kind of function is called immediate execution function. Immediately executed functions tend to be executed only once. Because there is no function name, it cannot be called again later.

(function(){
    
    
	console.log('我是立即执行函数');
})(); // 后面的括号表示掉这个匿名函数
2.Formal parameters and actual parameters

The value of the parentheses when creating the function is the formal parameter (formal parameter), and the value passed in when calling the function is the actual parameter (actual parameter)

function fun(a,b){
    
    } // a和b是形参
fun(1,2); // 1和2是实参

Declaring formal parameters is equivalent to defining two variables with the same name inside the function, but without assigning values.

  1. The parser does not check the type of the actual parameters when calling the function
// 求两数的和
function sum (a,b){
    
    
	console.log('他们的和是:'+(a+b));
}
sum(1,2); // 3
sum(true,false); //1
sum(123,'Hello'); //123Hello

Therefore, you should pay attention to whether you may receive illegal parameters. If possible, you need to type check the parameters, because the actual parameters of the function can be any data type.

  1. The parser also does not check the number of arguments when calling a function
// 求两数的和
function sum (a,b){
    
    
	console.log('他们的和是:'+(a+b));
}
sum(1,2,3,4); //3
sum(1); // 1+undefined=NaN

Excess actual parameters will not be assigned.
If the number of actual parameters is less than the number of formal parameters, the formal parameters without corresponding actual parameters will be undefined.

3.Return value

Functions can return values ​​through return

// 求两数的和
function sum (a,b){
    
    
	return a+b;
	console.log('hahahaha'); //return后的语句不会执行
}
var result = sum(1,2); 
console.log(result);

The value after return will be returned as the execution result of the function. You can define a variable to receive the result. The
statement after return in the function will not be executed. If the return statement is not followed by any value, it is equivalent to returning an undefined. If If return is not written in the function, undefined will also be returned.

4. The relationship between objects and functions

Object properties can also be functions

var obj = new Object();
obj.name = 'swk';
obj.say = function(){
    
    
	console.log('Hello');
}
console.log(obj.say);
console.log(obj.say());

A function can become an attribute of an object.
If a function is saved as an attribute of an object, then we call the function a method of the object. Calling this function
means calling the method of the object,
but the difference between a method and a function is only in name and nothing else. the difference

5. Enumeration object properties
var obj = {
    
    
	name:'zbj',
	age:19,
	gender:'男',
	address:'花果山'
};
for(var n in obj){
    
    
	console.log('属性名:'+n);
	console.log('属性值:'+obj[n]);
}
6. Advance declaration of functions and variables
  1. Declaration of variables in advance.
    Variables declared using the var keyword will be declared before all code is executed (but will not be assigned a value).
    However, if the var keyword is not used when declaring the variable, the variable will not be declared in advance.
console.log(a); //不会报错,但是输出undefined
console.log(b); // 报错
var a = 123;
b = 123
  1. The function is declared in advance.
    For functions created using the function declaration form, function function name (){}
    will be created before all code is executed, so we can call the function before the function declaration.
    For functions created using function expressions, will not be declared ahead of time, so it cannot be called before declaration
fun();  //可以执行
fun2(); // 报错
function fun(){
    
     //函数声明,会被提前创建
	console.log('我是函数声明形式创建的函数');
}
var fun2 = function(){
    
     // 函数表达式,fun2会被声明,他的值为undefined,但是函数不会被创建
	console.log('我是函数表达式创建的函数');
}
7.Scope

Scope refers to the scope of a variable

There are two types of scopes in JS:

  1. Global scope
    JS code written directly in the script tag is in the global scope. The global scope is created when the page is opened and destroyed when the page is closed.
    There is a global object window in the global scope, which represents a browser window. It is created by the browser and we can use it directly.
    In the global scope:
    the created variables will be saved as attributes of the window object, and the functions will be saved as methods of the window object. The variables in the global scope are global variables and can be accessed in any part of the page.
console.log(window); // window是个对象
var a = 123;
console.log(window.a); // 全局变量a也是window的属性
function fun(){
    
    
	console.log('我是window的方法');
}
window.fun(); // 创建的函数fun也是window的方法

Insert image description here
2. Function scope:
A function scope is created when a function is called. After the function is executed, the function scope is destroyed. Each time a function is called, a new function scope is created. They are independent of each other.
Variables in the global scope can be accessed in the function scope, but variables in the function scope cannot be accessed in the global scope.

var a = 123;
function fun() {
    
    
	console.log(a); // 123
	var b = 456;
}
fun();
console.log(b); //报错 b is not defined

When operating a variable in the function scope, it will first search for it in its own scope. If it exists, it will be used directly. If not, it will search in the upper-level scope until it finds the global scope. If there is still no such variable in the global scope, it will be used directly. If found, a ReferenceError will be reported.

var a = 123;
var b = 456;
function fun() {
    
    
	var a = 'hello';
	var b = 789;
	console.log(a); // hello
	function fun2() {
    
    
		console.log(b); //789
		console.log(c); //ReferenceError: c is not defined
	}
	fun2();
}
fun();

To access global variables in a function, you can use the window object.
When creating a variable, if the var keyword is not used, the created variable will become a global variable.

Note: Use delete to delete the properties of an object. In the same way, you can delete the properties of window. If you do not use var to create variables (properties of the window object), you can use delete to delete them. However, variables created with var (also properties of the window object) can be deleted using delete. ) cannot be deleted using delete, because the configurable attribute of a variable created using var defaults to false, so it cannot be deleted using delete. You can view the "property internal object" of the object's properties through Object.getOwnPropertyDescriptor(object,'property name')

var a = 10;
function fun() {
    
    
 	var a = 123;
 	console.log(window.a); // a = 10  通过window,可以访问到被局部变量覆盖后的全局变量
 	b = 456; // 没有使用var 创建变量,所以b是全局变量
 	a = 789; 
 	console.log(a); // 789
}
fun();
console.log(b); // 456
console.log(a); // 10

There is also the feature of early declaration in function scope.
Variables declared using the var keyword will be declared before all code in the function is executed. Function declarations will also be executed before all code in the function is executed.

var a = 111;
function fun() {
    
    
	fun2(); //提前声明和赋值,输出123
	console.log(a); //变量提前声明,但是没有赋值,所以a=undefined,即使有全局变量a,a还是undefined
	var a = 123;
	function fun2() {
    
    
		console.log('123');
	}
}
fun();
8.this

Every time the parser calls a function, it passes an implicit parameter into the function. This implicit parameter is this, and this points to an object. This object is called the context object of function execution.
Depending on how the function is called, this will point to different objects.
1. When called as a function, this is always window
. 2. When called as a method, this is the object that calls the method.

function fun() {
    
    
	console.log(this); //this是一个隐含传入的参数
	console.log(this.name);
}
var obj = {
    
    
	name:'swk',
	say:fun
}
var obj2 = {
    
    
	name:'zbj',
	say:fun
}
var name = 'shs';
obj.say(); // swk,以方法的形式调用时,this就是调用方法的那个对象
obj2.say(); // zbj
fun(); //shs, 以函数的形式调用时,this永远都是window
console.log(obj.say == fun);  //true代表两者是同一个地址的函数
console.log(obj2.say == fun);
console.log(obj.say == obj2.say);

Insert image description here

9. Constructor

The constructor is an ordinary function. The creation method is no different from that of ordinary functions. The difference is that the first letter of the constructor is capitalized.

function Person(name,age,gender){
    
     //首字母大写
	this.name = name;
	this.age = age;
	this.gender = gender;
	this.say = function(){
    
    
		console.log('你好!');
	}
}
var per = new Person('swk',18,'男'); // 使用new是调用构造函数Person,不使用new则是调用普通函数Person
var per1 = new Person('zbj',28,'男'); //我是Person类的一个实例
var per2 = new Person('shs',38,'男'); //我也是Person类的一个实例

function Dog(name,age){
    
    
	this.name = name;
	this.age = age;
	this.say = function(){
    
    
		console.log('汪汪~~');
	}
}
var dog = new Dog('柴犬',1); //我是Dog类的一个实例
console.log(per); // Person {name: "swk", age: 18, gender: "男", say: ƒ}
console.log(dog); // Dog {name: "柴犬", age: 1, say: ƒ}

The difference between a constructor and an ordinary function is the calling method.
Ordinary functions are called directly, while constructors need to be called using the new keyword.
The execution flow of the constructor:
1. Create a new object immediately
2. Set the newly created object to This in the function, you can use this in the constructor to refer to the newly created object
3. Execute the code in the function line by line
4. Return the newly created object as the return value

Objects created using the same constructor are called a class of objects, and a constructor is called a class. We will call the object created through a constructor an instance of the class

The situation of this:
1. When called in the form of a function, this is window
2. When called in the form of a method, whoever calls the method this is who
3. When called in the form of a constructor, this is the newly created one object

console.log(per instanceof Person); //true
console.log(dog instanceof Person); //false
console.log(dog instanceof Dog); //true
console.log(dog instanceof Object); //true
console.log(Dog instanceof Object); //true

Use instanceof to check whether an object is an instance of a class, syntax: object instanceof constructor
If so, return true, otherwise return false
Object is the parent class of all classes, all objects are descendants of Object, all objects and classes do instanceof will return true when querying

10. prototype

Every function we create, the parser adds an attribute prototype to the function

This attribute corresponds to an object, which is what we call a prototype object.

  • If the function is called as a normal function prototype has no effect

  • When a function is called as a constructor, the object it creates will have an implicit property, see below

function MyClass() {
    
    
}
function Person() {
    
    
}
console.log(MyClass.prototype); // 每个构造函数都有prototype
console.log(Person.prototype);
console.log(Person.prototype == MyClass.prototype); // false,每个构造函数的prototype都不同
  • Points to the prototype object of the constructor. We can access this property through __proto__, see below
function MyClass() {
    
    
}
var mc = new MyClass();
console.log(mc.__proto__);
console.log(mc.__proto__ == MyClass.prototype); // true

Insert image description here

  • The prototype object is equivalent to a public area. All instances of the same class can access this prototype object. We can uniformly set the common content in the object to the prototype object.

  • When we access a property or method of an object, it will first search for it in the object itself. If it exists, it will be used directly. If not, it will search for it in the prototype object. If it is found, it will be used directly. See below

function MyClass() {
    
    
}
MyClass.prototype.a = 123;
var mc = new MyClass();
console.log(mc.a); // 123
mc.a = 456;
console.log(mc.a); //456
  • When we create a constructor in the future, we can add the properties and methods common to these objects to the prototype object of the constructor. In this way, we do not need to add it to each object separately, and it will not affect the global scope, so that each object can be Objects all have these properties and methods
function Person(name,age,gender) {
    
    
	this.name= name;
	this.age = age;
	this.gender = gender;
}
Person.prototype.say = function() {
    
    
	console.log('Hello,我是:' + this.name);
}
var per = new Person('swk',18,'男');
var per2 = new Person('zbj',28,'男');
per.say();
per2.say();

Prototype chain
The prototype object is also an object, so it also has a prototype.
When we use the properties or methods of an object, we will look for them in itself. If there is one in itself, we will use it directly.
If not, we will look for it in the prototype object. If it is in the prototype object If there is, use it.
If not, search for the prototype of the prototype until you find the prototype of the Object object.
The prototype of the Object object has no prototype. If it is still not found in the Object, undefined is returned.

function MyClass() {
    
    
}
var mc = new MyClass();
// 在对象的原型中查找hasOwnProperty方法
console.log(mc.__proto__.hasOwnProperty('hasOwnProperty')); //false
// 在对象的原型的原型中查找hasOwnProperty方法
console.log(mc.__proto__.__proto__.hasOwnProperty('hasOwnProperty')); // true
console.log(mc.__proto__.__proto__); // 对象原型的原型
console.log(mc.__proto__.__proto__.__proto__); // null 没有对象原型的原型的原型
11. Garbage Collection (GC)
  • Just like people will generate garbage as they live for a long time, garbage will also be generated during the running of the program. When too much garbage accumulates, it will cause the program to run too slowly. So we need a garbage collection mechanism to handle the garbage generated during the running of the program.
  • When an object does not have any variables or attributes to reference it, we will never be able to operate the object. At this time, this object is garbage. Too many such objects will occupy a lot of memory space, causing the program to run slowly. , so this kind of garbage must be cleaned up.
  • There is an automatic garbage collection mechanism in ]S, which will automatically destroy these garbage objects from memory. We do not need and cannot perform garbage collection operations.
  • All we need to do is set null for objects that are no longer used.
    Insert image description here

7. DOM

1. What is DOM?
  • DOM, the full name is Document Object Model.
  • JS operates HTML documents through DOM
  • The Document
    document represents the entire HTML page
  • The Object
    object represents converting each part of the web page into an object.
  • Model Model
    uses models to represent the relationships between objects, which makes it easier for us to obtain objects.
    Insert image description here
2.Node
  • Node is the most basic component of our web page. Every part of the web page can be called a node . For example: html tags, attributes, text, comments, the entire document, etc. are all nodes.
  • Although they are both nodes, their specific types are actually different. For example: labels are called element nodes, attributes are called attribute nodes, text is called text nodes, and documents are called document nodes .
  • Different types of nodes have different properties and methods.Insert image description here
    Insert image description here
Document nodeDocument
  • The document node document represents the entire HTML document, and all nodes in the web page are its child nodes.
  • The document object exists as a property of the window object, and we can use it directly without obtaining it.
  • Through this object we can find node objects within the entire document access, and we can create various node objects through this object.
Element nodeElement
  • Various tags in HTML are element nodes, which is also the most commonly used node.
  • The browser will convert all tags in the page into an element node, and we can obtain the element node through the document method. For example:
    document.getElementByld()
    obtains an element node object based on the id attribute value.
Text nodeText
  • Text nodes represent text content other than HTML tags. Any non-HTML text is a text node. It includes plain text content that can be interpreted literally.
  • Text nodes generally exist as child nodes of element nodes.
  • When getting text nodes, you generally need to get element nodes first. Get the text node through the element node. For example:
    element node.firstChild;
    gets the first child node of the element node, which is usually a text node.
Attribute node Arrt
  • The attribute node represents each attribute in the tag. It should be noted here that the attribute node is not a child node of the element node, but a part of the element node.
  • The specified attribute node can be obtained through the element node. For example:
    element node.getAttributeNode("attribute name")
    Note: We generally do not use attribute nodes.
3.Event
  • Events are specific moments of interaction that occur within a document or browser window.
  • The interaction between JavaScript and HTML is achieved through events.
  • For web applications, there are the following representative events: clicking on an element, moving the mouse over an element, pressing a key on the keyboard, etc.
event object

When the event response function is triggered, the browser will pass an event object as an actual parameter into the response function each time , and all information related to the current event is encapsulated in the event object, such as: the coordinates of the mouse, which button on the keyboard was pressed The direction in which the mouse wheel scrolls. . .

btn.onclick = function(event) {
    
    
	console.log('我是事件对象:' + event);
}
dissemination of events

The bubbling HTML of the event
is shown as follows: three divs each with a
Insert image description here
JS code as follows:

window.onload = function() {
    
    
	var one = document.getElementById('one');
	var two = document.getElementById('two');
	var three = document.getElementById('three');
	one.onclick = function() {
    
    
	console.log('我是青色方块!')
	}
	two.onclick = function() {
    
    
		console.log('我是绿色方块!')
	}
	three.onclick = function() {
    
    
		console.log('我是黄色方块!')
	}
}

Insert image description here
When I click on the yellow square, logically only one event will be triggered, but all three events are triggered. This situation is the bubbling of events.
Clicking on the target element will trigger the same event on the element's ancestor elements .

dissemination of events

  1. Capture phase
    In the capture phase, events are captured from the outermost ancestor element to the target element, but by default the event will not be triggered at this time.
  2. Target phase:
    The event captures the target element. After the capture ends, the event starts to be triggered on the target element.
  3. In the bubbling phase
    , the event is passed from the target element to its ancestor elements, and the events on the ancestor elements are triggered in turn.
    Insert image description here
    If you want to trigger the event in the capture phase, you can set the third parameter of addEventListener() to true. Generally, we do not You will want to trigger the event during the capture phase, so this parameter is generally false.
    There is no capture phase in browsers IE8 and below
// addEventListener()函数
addEventListener(eventStr, callback, false){
    
    
// eventStr:事件的名称,不带on,例如click
// callback:回调函数
// false:如果为false,则捕获阶段不会触发事件,如果为true,捕获阶段会触发事件
}
4.BOM object

BOM: Browser Object Model
BOM allows us to operate the browser through JS. The BOM provides us with a set of objects to complete the operation of the browser - BOM objects

  • Window
    represents the entire browser window, and window is also the global object in the web page.
  • Navigator
    represents the information of the current browser. This object can be used to identify different browsers.
  • Location
    represents the address bar information of the current browser. You can obtain the address bar information through Location, or operate the browser to jump to the page.
  • History
    represents the browser's history. You can use this object to operate the browser's history.
    Due to privacy reasons, this object cannot obtain specific history records. It can only operate the browser to page forward or backward, and this operation is only available in Valid for the current visit
  • Screen
    represents the information of the user's screen. Through this object, the relevant information of the user's display can be obtained.
console.log(window);
console.log(navigator);
console.log(Location);
console.log(history);
console.log(screen);

Insert image description here
These BOM objects are saved as properties of the window object in the browser and can be used through the window object or directly.

5.JSON

JavaScript Object Notation JS Object Notation

  • JSON is a string in a special format. This string can be recognized by any language and can be converted into an object in any language. JSON is mainly used for data interaction in development.
  • The format of JSON and JavaScript objects are the same, except that the attribute names in the JSON string must be enclosed in double quotes. The other syntax is consistent with JavaScript.
JSON —> JS object

JSON.parse()

  • Can convert JSON string to JS object
  • It takes a JSON string as parameter and will convert the string into a JS object
var json = '{"name":"swk","age":18}'; // JSON格式的数据
var obj = JSON.parse(json); // 将JSON格式数据转为JS对象
console.log(typeof json); // JSON的类型:string
console.log(typeof obj); // 转换后的类型:object
JS object —> JSON

JSON.stringify()

  • Can convert a JS object into a JSON string
  • A JS object is required as a parameter and a JSON format string will be returned.
var obj = {
    
    name:"zbj", age:18, gender:"男"}; // JSON格式的数据
var json = JSON.stringify(obj); // 将JSON格式数据转为JS对象
console.log(typeof json); // 转换后的类型:string
console.log(typeof obj); // JS对象类型:object

8. Finally

Finally, I recommend Teacher Ruan Yifeng’s "Introduction to JavaScript Language Tutorial"

Guess you like

Origin blog.csdn.net/weixin_46683645/article/details/116067284