js basic ~ array, object, function, math object, DOM node

Posted by v3nt on Wed, 09 Feb 2022 22:02:11 +0100

1. Array

(1) When storing multiple data of the same type, you can use array, which is a reference type.

  • Two ways to create arrays
//The first creation method Use the new keyword
var nameList = new Array();
//The second creation method uses [] literal.
var nameList = [];

(2) Data is stored by index (sequence number) in the number, and the data is orderly in the array. The data in the array can be accessed through the index, which starts from 0.

var arr = [1,2,3];
console.log(arr[0])  //1

(3) An array is also an object. Therefore, the array also has attributes, in which the length attribute represents the length of the array, that is, the number of elements in the array.

 var arr = [1,2,3];
    console.log(arr.length)   //3

2. Common methods of array

  • arr[0] uses the index to read and write the elements in the array.
  • The push method is used to append an element to the last element of the array.
 var arr = [1,2,3];
    console.log(arr[0])   //3
    arr.push(4);
  • pop is used to delete the last element in the array, and the return value is the deleted element.
var arr = [1,2,6];
    console.log(arr.pop())  //6

push and pop in the array are a pair of stacks. Stack is a linear data structure. There is only one entry and also an exit. First in first out, last in first out.

  • unshift: adds an element to the front of the array.
var arr = [1,2,6];
    arr.unshift('a')
    console.log(arr)   //[ "a", 1, 2, 6 ]
  • shift: deletes an element from the front of the array, and the return value is also the deleted element.
var arr = [1,2,6];
console.log(arr.shift()) //1

Shift and unshift are also a pair of stack operations. Push and shift are a pair of queue operations. Queue is a linear data structure, first in first out, last in and last out.

  • Splice: there are three parameters, which are used to add or delete elements to the array:
1 Parameter (first parameter): where to start deletion(According to index),
2 Parameter: delete several elements,
3 Parameter: replace new element after deletion
 The first two parameters are required and the latter are optional
var arr1 = ['a','b','c'];
    arr1.splice(2,1,99,88);
    console.log(arr1)   //[ "a", "b", 99, 88 ]
  • Reverse: used to reverse the order of elements in the array:
var arr1 = ['a','b','c'];
    arr1.reverse()
    console.log(arr1)  //[ "c", "b", "a" ]
  • Slice: used for array interception, with 2 parameters.

1 Parameter: from which position to intercept (including)
2 parameter: where to intercept (excluding the current position element), return the intercepted content to the new array, and the original array remains unchanged.
If the second parameter is not written, it is intercepted to the end.
If the second parameter is written with - N, it means that the penultimate n is intercepted.

var arr1 = ['a','b','c','d','e'];
    console.log(arr1.slice(1,3))   //[ "b", "c" ]
  • Indexof: gets the index of the first occurrence of the element in the array. If it is not included, it returns - 1.
var arr1 = ['a','b','c','d','e'];
   console.log(arr1.indexOf('c'))  //2
   console.log(arr1.indexOf('w'))  //-1
  • Join: concatenates the contents of the array into a string.
var arr1 = ['a','b','c','d','e'];
    var str = arr1.join('')
    console.log(str)  //abcde

3. String object

character string.startsWith  ,Used to judge whether this string starts with the parameter string,
	The return value is a Boolean value. If yes, it is returned true,Not return false. 
character string.endsWith() : Judge whether this string ends with another string.
  • character string. Length indicates the number (length) of characters in this string.
  • character string. substr() method, used for string interception,

1 reference: cut from the first few words,
2 parameter: how many words are cut,
The return value is the intercepted new string. If the second parameter is not passed, it is intercepted to the end of the string.

  • character string. substring() method, string interception,

1 reference: cut from the first few words (including),
2. Reference: the first few words (not included) are intercepted.

The difference between substr and substring

Same point: when there is only one parameter, both of them are the string fragments intercepted from the current subscript to the end of the string

let str = 'abcdefgh'
    console.log(str.substr(3))  //defgh
    console.log(str.substring(3))  //defgh

Differences: when there are 2 parameters:
substr (satrt,end): the second parameter is the length of the intercepted string (intercepting the end length string from the starting point);
substring (satrt,end): the second parameter is to intercept the final subscript of the string (intercept the string between two positions, 'including head and not including tail').

let str = 'abcdefgh'
    console.log(str.substr(2,5))    //cdefg
    console.log(str.substring(2,5))  //cde
  • character string. Split (separator):

Used for string separation. The parameter is a separator. The return value is an array, which contains all strings after separation.
a. If the delimiter is an empty string, each character of the string is separated.

let str = 'abcde'
    console.log(str.split(''))  //Array(5) [ "a", "b", "c", "d", "e" ]

b. If the delimiter parameter is not filled in, the original string is returned in the array

let str = 'abcde'
    console.log(str.split()) //Array [ "abcde" ]
  • Check whether the current string contains the target string, return the bool value, and true represents the target string
let str = "abc123qwertyu"
    ind =str.includes("23q");
    console.log(ind);  //true
  • Valueof is a string method that takes out the string value passed in. This method can also be used for numeric and Boolean types.
var strObj =new String("123");
var str2 =strObj.valueOf();
console.log(str2);   //123

4. function

(1) Function: declare a function,
(2) Function format: function function name (parameter list) {function body},

function people(name, age, sex) {}

(3) The format of function call is: (function name (argument list), argument: actual parameter),

 people("Xiao Ming", 30, true);

(4) When calling a function, the code in the function body of the function will be executed, and the parameter value in the function is passed in this call,
(5) Parameter value, the function call itself is also an expression, and the value of the expression is the return value of the function,
(6) Scope of function:

Scope: each parameter has a scope. If it exceeds the scope, it will become invalid. This scope is called scope.

5. Data type in JS

There are two types of data in js:
1. Basic data type; String type, numeric type, boolean type
2. Reference data type: all objects are reference types,

Difference between basic data type and reference data type:
The basic data type saves the value, and the reference type saves the memory address.

6. Object

(1) Object: a complex data type that integrates variables and functions.
Three characteristics of objects: encapsulation, inheritance and polymorphism.

Objects can also be created in two ways:
1.new: open up memory and Object() construct the function of the object. Object declaration and implementation can be written together.

let obj = new Object();

The literal method can also be used to create objects

var obj3 = {
        // When creating literal quantity, attribute and attribute should be separated
        name: "eldest brother",
        major: "student",}
}

(2) Attribute assignment is the same as regular variable assignment. Only the object is needed when calling Property name.

obj.age = 20;
obj.sex = "male";
//When calling
console.log(obj.age);  //20

(3) When the assignment behind the attribute of an object becomes a function, this attribute is called the method of the object. Calling: objects Method name.

let obj = new Object();
 obj.eat = function () {
        console.log("I ate five meat buns this morning");
    }   
    //When calling
    obj.eat();

(4) An object is a container in which data appears in the form of key value pairs. In the following object man: name is the key and big brother is the value. Value is obtained by key.
(5) Delete an object's properties

Format: delete object attribute

(6) Another access method of object: value according to the key, and double quotation marks should be used inside [] to wrap the key name.

 var man = new Object();
    man.name = "eldest brother";
	man.age = 1;
	//When taking value
	 console.log(man["name"]);  //eldest brother 

(7) The property of an object can also be an object.

//Express traversal of object properties
Forin Loop: it is specially used for traversal of object attributes, key Represents an empty property.
hold obj The above attribute is assigned to key
for (var key in obj) {
	//Other logic
}

7. Sealing (packing) operation

When calling a method with a basic data type, the js executor will temporarily create a corresponding object based on this type to encapsulate this basic data type. When using this basic data type to call a method, it is actually the method provided by the object preset by the system. After using it, the object will be automatically released and become the initial value. This process is called sealing operation, which is used to reduce the burden of programmers.

8.Math object:

Math object is an object of js built-in object. The appearance of built-in object is mainly to solve a single function.
(1) Common methods of Math object

  • Number comparison.
math.max Bigger than
console.log(Math.max(5,3));
math.min Smaller than

Rounding
console.log(Math.round(3.5));
Round down
console.log(Math.floor(3.5));
Round up
console.log(Math.ceil(3.5));
random number
console.log(Math.random());

(2) Other methods for math objects

  • PI (required for circle animation): math PI.
console.log(Math.PI);

Natural logarithm: math E
console.log(Math.E);
Calculate the absolute value of a number
onsole.log(Math.abs(-4));
Power operation, calculate the y power of x
console.log(Math.pow(x,y));
Open square
console.log(Math.sqrt(25));
Open multiple square
console.log(Math.pow(27,1/3));
Trigonometric function, sinusoidal function. 30 represents angle (only radians can be recognized in programming language, so radians can be obtained by passing in angle)
console.log(Math.sin(30*Math.PI/180));
// Math.cos cosine math Tan tangent math Cot cotangent

9. Non Boolean values are used as Boolean values

If judgment, the judgment conditions need to write Boolean values or Boolean expressions.

  • If a non Boolean value is written into the if condition, the value will be forcibly converted to a Boolean value when the program is executed.
  • If the numeric type is used as a Boolean value, then 0 is false and the rest are true.
  • If the string type is used as a Boolean value, the empty string is false and the non empty string is true.
  • If the object is judged as a judgment condition, as long as the object has memory, the result is true.
  • Null: indicates that the current content to be read cannot be read. It is also false.
  • If the value of the parameter is NAN, or non numeric values such as string, object and undefined cannot be read out, special functions are used for judgment.

isNAN function: judge the variable and return true if it is satisfied. Used to detect whether the variable is a, yes, non numeric value.

if (Number.isNaN(v2)==true) {
        console.log("I can't read it");
    }

Using logical operators on non Boolean values will convert non Boolean values into Boolean values before calculation.

let s1 = 45
    console.log(!!s1);   //true

10.DOM node

DOM(document object model) document object model.
dom structure (dom tree): after opening an html page, the browser will render all the tags in the currently opened html page and parse each tag into an object. These objects are associated with each other in a tree structure. This structure is the dom structure, that is, the so-called dom tree. These tags will be stored in document after parsing. Document is an object collection of page body tags, which is called document object model.

All operations on page objects need to be accessed through document. Tags and styles are converted into objects or methods through dom. html tags cannot be directly operated in js.

  • document represents the object of the current page. getElementById: find elements by id. Once found, it will be returned as an object.
 var obj =document.getElementById("title");
    console.log(obj)
  • getElementsByTagName: find all elements that match the tag name. Returns a list.

A list is not a real array, but you can use indexes to access elements like an array, or you can use length.

var p1 =document.getElementsByTagName("p");
  • getElementsByClassName: find the matching elements according to the class style and return a list.
var lines =document.getElementsByClassName("line");
  • querySelector: find an element based on the style selector. What is returned is the queried page element object.
var hello =document.querySelector("#title");
  • querySelectorAll: find all qualified elements according to the style selector and return the list.
var linqwe=document.querySelectorAll(".line")

==The difference between textContent and innerHTML==

textContent displays a single text, regardless of the text content. innerHTML will parse the tags in the content into elements and display them when setting the content.

Topics: Javascript array Functional Programming DOM