[JavaScript learning record 3] new array (Integration Exercise 1, various methods), arguments, new Data, math, new wrapper class, String, new RegExp regular expression


1.1 Array object method creation - array

//var arr = new Array();
var arr = new Array(0,1,22);

------Adds an element to the last position of the array

1.2 literal method creation - array

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

------Create an array with only one element in it
------Create an array with a length of 10
arr2=new Array(10);

-------The elements in the array can be any data type----------------------------------------

-------It can also be an object
var obj={name:"Sun WuKong"};
arr=[{name:"Monkey King“},{name:"Sand monk"},{name:"Zhu Bajie"}];

-----It can also be a function

1.3 four operations of array

  • push()
    -This method can add one or more elements to the end of the array and return the new length of the array
    -You can pass the elements to be added as parameters of the method, so that these elements will be automatically added to the end of the array
    -This method returns the new length of the array as the return value
var result=arr.push("Tang Monk "," spider essence "," white bone essence "," jade free essence ");
  • pop()
    -This method can divide the last element of the array and return the deleted element as the return value
  • unshift()
    -Adds one or more elements to the beginning of the array and returns the new array length
    -After inserting the element forward, the indexes of other elements will be adjusted in turn
arr.unshift("Ox demon king "," Erlang God ");
  • shift()
    -You can divide the first element of the array and return the divided element as a return value

1.4 array traversal

var arr=["Monkey King "," pig Bajie "," sand monk "," Tang Monk "];
for(var i=0; i<arr.1ength;i++){


function Person(name,age,gender){
//Modify toString of Person prototype 
//Create a Person object
var per=new Person("Monkey King ", 18);
var per2=new Person("Pig Bajie ", 28);
var per3=new Person("Red boy ", 8);
var per4=new Person("Spider essence ", 16);
var per5=new Person("Two solutions to God ", 38);

------------These person Object into an array----------------
var perArr=[per,per2,per3,per4,per5];

function getAdult(arr){
	//Create a new array
	var newArr = [];
	//Traverse the ARR to get the Person object in the arr
	for(var i=e;i<arr.1ength;i++){
		var p = arr[i];
		//Determine whether the age of the Person object is greater than or equal to 18
			//If greater than or equal to 18, this object is added to newArr
			//Put objects into a new array
	return newArr;   //Returns the updated array

var result = getArr(perArr)
console. log(result);

1.5 array foreach() traversal

var arr=["Monkey King "," pig Bajie "," sand monk "," Tang Monk "," Baigujing "];
	console.log("hello");    //As a result, five hello

	console.log("a="+a);   //Results: Monkey King pig Bajie sand monk Tang Monk Baigujing

----ForEach()Method requires a function drum as a parameter
-----This function, which is created by us but not called by us, is called a callback function
-----There are several elements in the array, and the function will be executed several times. Each time, the browser will pass the traversed elements in the form of arguments. We can define open formal parameters to read these contents
-----The browser will pass three parameters in the callback function:
---------The first parameter is the element currently being traversed
---------The second parameter is the prime index of the element currently being traversed
---------The third parameter is the array being traversed

*The forEach () method requires a number of paintings as a parameter
*-Functions like this, created by us but not called by us, are called callback functions
*-If there are several elements in the array, the function will be executed several times

1.6 extraction, modification and deletion of array slice() and splice fragments

  • slice()
    -You can use I that does not extract the specified element from the array
    -This method does not change the element array, but encapsulates the intercepted elements into a new array and returns
    1. The index of the location where the interception starts, including the start index
    2. The index of the position where the interception ends, excluding the end index
    -The second parameter can be omitted without writing. At this time, all elements from the beginning of the index will be intercepted
    -The index can pass a negative value. If it passes a negative value, it will be calculated from back to front
    -1 penultimate - 2 penultimate
var result=arr.slice(1,4); 
result=arr. slice(3);
result=arr. slice(1,-2); 
console. log(result);
  • splice()
    -Can be used to divide a specified element in an array
    -Using splice () will affect the original array, delete the specified element from the original array, and return the deleted element as the return value
    The first one is the index indicating the starting position
    The second represents the number of divisions
    Third and later..
    You can pass some new elements, which will be automatically inserted in front of the start position index
arr=["Monkey King "," pig Bajie "," sand monk "," Tang Monk "," Baigujing "];
var result=arr.splice(1,0,Ox demon king "," Iron Fan Princess "," hong'er ");

Results: "Monkey King, ox demon king, Princess Iron Fan, red boy, pig Bajie, sand monk, Tang monk, Baigujing"

1.7 other array methods (concat, join, reverse, sort)

var arr=["Monkey King "," pig Bajie "," sand monk“];
var arr2=["Baigujing "," jade rabbit essence "," spider essence "];
*concat()You can connect two or more arrays and return the new array
*-This method will not affect the original group
var result=arr.concat(arr2);console.1ogdresult);
Results: "Monkey King, pig Bajie, sand monk, Baigujing, yumianjing, spider essence"

-This method can convert the array to a string
-This method does not affect the original array, but returns the converted String as the result
-In join (), you can specify a string as a parameter, which will become the connector of the elements in the array
-If no connector is specified, it is used by default as the connector*/
arr=["Monkey King "," pig eight precepts "," monk Sha"];
result:"Sun WuKong@-@Zhu Bajie@-@"Sand monk"

-This method is used to invert the array (the front edge goes to the back edge, and the rear edge goes to the front edge)
-This method will directly modify the original array

By default Unicode Sort by code
arr. sort();

We can adopt the rules of designated worship order
 We can sort()Add a callback function to specify the collation
---Two formal parameters need to be defined in the callback function. The browser will use the elements in the array as arguments to call the callback function
---It's not certain which element to call, but it's definitely in the array a Must be b in front
 The browser will determine the order of elements according to the return value of the callback function,
---If a value greater than 0 is returned, the element swaps positions
---If a value less than 0 is returned, the element position remains unchanged
---If a 0 is returned, the two elements are considered equal and the positions are not exchanged

	//Ascending arrangement
	return a-b;
	//Descending order
	return b-a;

1.8 ca11 () and apply () and this

  • ca11() and apply()
    -Both methods are methods of function objects, which need to be called through function objects
    -When calling ca11 () and apply () to the function, the function will be called to execute
    -When calling ca11 () and apply (), you can specify an object as the first parameter. At this time, the object will become this when the function is executed
    -The call () method can pass arguments after the object in turn
    -The apply () method needs to encapsulate the arguments into an array and pass them uniformly
function fun(a,b){
console. log("a="+a); console. log("b="+b);
fun.cal1(obj);    //a=undefined ...
fun.call(obj,2,3);   //a=2   b=3
  • this situation:
    1. When called as a function, this is always window
    2. When calling in the form of a method, this is the object that calls the method
    3. When called in the form of constructor, this is the newly created object
    4. When calling with cal1 and app1y, this is the specified object

2. Save arguments (and instanceof)

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

  • 1. The context object this of the function
  • 2. Object arguments encapsulating arguments
    • arguments is a class array object. It can also manipulate data through index or obtain length
    • When calling the function, the arguments we pass will be saved in arguments
    • arguments.length can be used to get the length of the argument
    • Even if we do not define formal parameters, we can use arguments through arguments, which is just troublesome
      arguments[e] represents the first argument
      arguments[1] indicates the second argument...
    • It has an attribute called callee, which corresponds to a function object, that is, the object of the function currently being pointed to
function fun(){
console. log(arguments instanceof Array); //false
console.1og(Array.isArray(arguments));  	//false

function fun(){
	console.1og(arguments[0]);   //1
	console.log(arguments.callee==fun);   //true

3 Data object (function)

//Create a Date object
//If you directly use the constructor to create a Date object, it will be encapsulated as the execution time of the current code var d=new Date();
//Creates a specified time object
//You need to pass a string representing time as an argument in the constructor

var d2=new Date("12/13/2011 11: 10: 30");

3.1 methods in data

  • getTime()
    • Gets the timestamp of the current date object
    • Timestamp refers to the number of milliseconds (1 second = 1000 milliseconds) spent from January 1, 1970, e hours, e minutes and e seconds of Greenwich mean time to the current date
    • The bottom layer of the computer uses time to save time
----------------Use time practice to test the performance of code execution
-------Get the current timestamp
var start=Date.now();
for(var i=0;i<100;i++){
	var end=Date.now();
Result: executed for: 2 ms

Other query technical documents: https://www.w3school.com.cn/index.html

4 Math tools

Other query technical documents: https://www.w3school.com.cn/index.html

5 packaging

  • Basic data type
    String Number Boolean Null Undefined
  • Reference data type

In JS, we are provided with three wrapper classes, through which we can convert the data of basic data types into objects

  • string()
    -You can convert a basic data type String to a String object
  • Number()
    -You can convert numbers of basic data types to 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 practical applications,
  • If you use basic data type objects, some unexpected results may be brought when making some comparisons
var num=new Number(3);   	output num=3
var num2=new Number(3);		output num2=3
----------however num!=num2----------------------
var s = 3;
s = s.toString();  
s.hello = "Hello";  //No error reporting
console.log(s.hello);  //undefined

Methods and attributes can be added to objects, but not to basic data types. When we call properties and methods on the values of some basic data types,
	The browser will temporarily use the wrapper class to convert it to an object,
		Then, after calling the properties and methods of the calling object, it is converted to the basic data type

In conclusion, the wrapper class is used for basic types (temporary conversion) at the bottom of the browser

6 String object

Other query technical documents: https://www.w3school.com.cn/index.html

7 RegExp object regular expression

  • Syntax: var variable = new RegExp("regular expression", "matching pattern");
    Using typeof to check regular objects will return object
  • var reg = new RegExp(“a”); This regular expression can be used to check whether a string contains a, and a matching pattern can be passed as the second parameter in the constructor,
    Can be
    • i ignore case
    • g global matching mode
var reg = new RegExp( "ab" , "i");
var str = "a";
*Regular expression method: * test()
-This method can be used to check whether a string conforms to the rules of regular expressions,
Returns true if it matches; otherwise, returns false
var result = reg.test(str);
console.log( result);
console.log(reg.test( "abcbc" ));

result: true

7.1 creating regular expressions using literals

*Use literals to create regular expressions
*Syntax: var variable = / regular expression / matching pattern*
---------Two representation methods------
var reg = new RegExp( "a" , "i");    ------This method can transfer variables, which is more flexible and convenient to change
reg = /a/i;

console. 1og(typeof reg);
console. log(reg.test( "abc"));

7.2 regular syntax

--------[]The content in is also the relationship between or
		[ab] == a | b
		[a-z]Any lowercase letter
		[A-Z]Any capital letter
		[A-z]Any letter
		[0-9]Any number
reg = /[A-z]/

--------Check whether a string contains abc or adc or aec
reg = /a[bde]c/ 

--------[^]except   						---Only in[Effective within] ,stay/ /Match start in
		[^ab]except ab
		[^0-9]Except numbers
		/ab{3}/ == /abbb/
		/(ab){3}/ == /ababab/  
		/ba{1,3}b/ ~~/bab/~/baab/~/baaab/ 1 to 3 in the middle b
		/ba{2,}/  baaaa....a More than 2 times
		/n+/ = /n{1,}/
		/n*/ = /n{0,}/
		/n?/ = /n{0,1}/
--------/^a/with a start  /a$/with a ending
		/^aasdas&/  Only aasdas

Rules applicable to machine number:
1 3 567890123(11 position)
1.Start with 1
2.Second 3-9 Any number is 3, and any number after three digits is 9

var phoneStr = "13567890123";
var phoneReg = /^1[3-9][e-9]{9}$/;
console. log(phoneReg.test(phoneStr));

Other syntax: other query technical documents RegExp Object: https://www.w3school.com.cn/index.html

7.2 method of String object supporting regular expression

search -- retrieves the value that matches the regular expression.
Match -- find a match for one or more regular expressions.
Replace -- replace substrings that match regular expressions.
split -- divides a string into an array of strings.

Other syntax: query technical documents RegExp object: https://www.w3school.com.cn/index.html

Tags: Javascript

Posted by zenix on Fri, 15 Apr 2022 01:08:05 +0930