Basic knowledge of JS (3)

array

Introduction to Arrays

An array is also an object, which is similar to ordinary objects and is used to store some values. The difference is that ordinary objects use strings as attribute values, while arrays use numbers as index elements

create array object

Get the length of the array:
For a continuous array, use the length attribute to get the length of the array (the number of elements)
For a non-continuous array, use the length attribute to get the maximum index of the array plus 1

Modify the length of the array:
if the modified length is greater than the original length, the extra elements will be vacated;
if the modified length is smaller than the original length, the extra elements will be deleted

//创建数组对象
var arr = new Array();
//使用typeof检查一个数组时,会返回object
//console.log(typeof arr)   object
//向数组中添加元素
arr[0] = 10;
arr[1] = 11;
arr[2] = 12;
//读取数组中的元素
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
//获取数组的长度
console.log(arr.length);
//修改数组的长度
arr.length = 10;
//向数组的最后一个位置添加元素
arr[arr.length] = 15;

array literal

Use literals to create arrays

//使用字面量来创建数组
var arr = [];
//使用字面量来创建数组时,可以在创建时就指定数组中的元素
var arr = [1,2,3,4,5];
//使用构造函数来创建数组时,也可以同时添加元素,将要添加的元素作为构造函数的参数进行传递
var arr = new Array(1,2,3,4,5);
//字面量
var arr1 = [10]; //创建一个数字,数组中只有一个元素
var arr2 = new Array(10);//创建长度为10的数组
console.log(arr1);// 10
console.log(arr2);//,,,,,,,,,  长度为10
//数组中的元素可以是任意的数据类型,也可以是对象,也可以是函数,也可以放数组
var arr3 = ["hello",1,true,null,undefined,{
    
    name:'猪八戒'},function(){
    
    alert(2)},[1,2,3]]
var obj = {
    
    name:'孙悟空'};
arr3.[arr.length] = obj;

Create a number with only one element in the array var arr1 = [10];
Create an array of length 10var arr2 = new Array(10);

Four methods of array

  1. push():
    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 length of the array.
    This method will array The new length is returned as the return value.
var arr = ['孙悟空','猪八戒','沙和尚']
var result = arr.push('唐僧','蜘蛛精','白骨精');
console.log(arr)//孙悟空,猪八戒,沙和尚,唐僧,蜘蛛精,白骨精
console.log(result);//6
  1. pop():
    This method can delete the last element in the array, call once to delete once,
    this method will return the deleted element as the return value
var arr = ['孙悟空','猪八戒','沙和尚']
var result = arr.push('唐僧','蜘蛛精','白骨精');
result = arr.pop();
console.log(arr)//孙悟空,猪八戒,沙和尚,唐僧,蜘蛛精
console.log(result);//白骨精
  1. unshift():
    Add one or more elements to the beginning of the array and return the new array length;
    after inserting elements like before, the indexes of other elements will be adjusted in turn
var arr = ['孙悟空','猪八戒','沙和尚']
var result = arr.push('唐僧','蜘蛛精','白骨精');
result = arr.unshift('牛魔王');
console.log(arr)//牛魔王,孙悟空,猪八戒,沙和尚,唐僧,蜘蛛精
console.log(result);//7
  1. shift()
    can delete the first element of the array and return the deleted element as the return value

Array traversal (forEach)

Traversing the data is to take out all the elements in the array

 for(var i=0;i<arr.length;i++){
    
    
   cosole.log(arr[i])
 }

You can also call the forEach() method to traverse (this method only supports browsers above IE8 )

The forEach() method requires a function as a parameter. Generally, an ordinary function is not passed in, because passing an ordinary function is equivalent to defining a function in the global scope, so the anonymous function is generally passed in.

var arr = ['孙悟空','猪八戒','沙和尚']
arr.forEach(function(){
    
    
	console.log('hello')
})

At this point, hello is printed 3 times directly

  • Functions like this, created by us but not called by us, are called callback functions. It can be easily understood that this function is called by the browser, and we just pass it to the browser
  • There are several elements in the array, and the function is executed several times. Each time it is executed, the browser will pass in the traversed elements as actual parameters.
var arr = ['孙悟空','猪八戒','沙和尚']
arr.forEach(function(a,b,c){
    
    
	console.log('a='+a)
	console.log('b='+b)
	console.log('c='+c)

})

Output:
a = 'Sun Wukong';
a = 'Zhu Bajie';
a = 'Sand Monk';
b = 0;
b = 1;
b =2;
c=Monkey King, Zhu Bajie, Sand Monk;
c=Sun Wukong, Zhu Bajie, Sand Monk
c=Monkey King, Zhu Bajie, Sha Monk

  • The browser will pass three parameters in the callback function:
  • The first parameter is the parameter (value) currently being traversed
  • The second parameter is the index of the element currently being traversed (index)
  • The third parameter is the array being traversed (obj)

splice and slice

slice:

  • The slice() method can return selected elements from an existing array
  • Syntax: arrayObject. slice(start, end)
  • Parameters: start: required, specifies where to start the selection, the starting position index of the interception, including the starting index. end: The index of the position where the interception ends, not including the end index. It can be omitted, and all elements from the start index onwards will be intercepted in this case. end can also pass a negative value, if a negative value is passed, it will be calculated from the back to the front.
  • This method will not change the original array , but encapsulate the intercepted elements into a new number and return

splice:

  • Can be used to delete, insert, and replace specified elements 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
  • Parameters: the first: the index indicating the starting position; the second: indicating the number of deletions; the third and later: some new elements can be passed, and these elements will be automatically inserted in front of the starting position index.

The remaining methods of the array

concat:

  • concat() can connect two or more arrays and return the new number
  • This method will not affect the original array
  • You can pass not only arrays, but also elementsvar result = arr.concat(arr1,arr2,"牛魔王","铁扇公主");

join:

  • This method converts an array to a string
  • Does not affect the original array , but returns the converted string as the result
  • In join(), you can specify a string as a parameter, and this string will become the connector of the elements in the array arr = ["孙悟空","猪八戒","沙和尚"]; result = arr.join('hello'); output'孙悟空hello猪八戒hello沙和尚'
  • If no connector is specified, commas are used by default as connectors. Use an empty string if no concatenation is desired.arr.join('')

reverse:

  • This method is used to reverse the array
  • will directly modify the original array

sort:

  • Can be used to sort the elements in an array
  • will also affect the original array
  • By default, it will be sorted according to the Unicode encoding. Even if the numbers correspond to pure numbers, when using sort() to sort, they will be sorted according to the Unicode encoding. Therefore, when sorting numbers, you may get wrong information.
  • We can specify the sorting rules ourselves, and we can add a callback function to sort() to specify the sorting rules. Two formal parameters need to be defined in the callback function, and the browser will use the elements in the array as actual parameters to call the callback function; it is uncertain which element to use to call, but it is certain that a must be in front of b in the array
  • If a value greater than 0 is returned, the elements will be exchanged; if a value less than 0 is returned, the element position will not change; if a value equal to 0 is returned, the elements will be equal and the position will not change
arr = [5,4,2,1,3,6,8,7]
arr.sort(function(a,b){
    
    
//前面的大
	if(a > b){
    
    
		return 1;
	}else if(a < b){
    
    
		return -1;
	}else{
    
    
		return 0;
	}
})

Equivalent to

arr = [5,4,2,1,3,6,8,7]
arr.sort(function(a,b){
    
    
	//升序排列
	return a - b;
})

Conclusion: ascending order: ab; descending order: ba

function (supplement)

call() and apply()

  • These two methods are methods of the function object and need to be called through the function object
  • When the function calls call () and apply () will call the function to execute
function fun(){
    
    
	alert("我是fun函数!");
}
fun.aaply();
fun.call();
  • An object can be specified as the first parameter when calling call and apply() . At this time, this object will become the this of the function execution.
  • The call() method can pass the actual parameters sequentially after the object fun.call(obj,2,3); while the apply() method needs to encapsulate the actual parameters into an array and pass them uniformlyfun.apply(obj,[2,3])

this summarizes:

  • When called as a function, this is window;
  • When called as a method, this is the object calling the method
  • When called as a constructor, this is the newly created object
  • When calling with call and apply, the object specified by this

arguments

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

  1. The function's context object this
  2. The object arguments that encapsulate the actual parameters

arguments:

  • arguments is an array-like object, it can also manipulate data by index, and can also get the length
  • When calling a function, the actual parameters we pass will be encapsulated in arguments
  • arguments.length can be used to get the length of the actual parameter
  • Arguments can be used to use actual parameters even if no formal parameters are defined. arguments[0] indicates the first actual parameter
  • arguments has a callee attribute, this attribute object is a function object, which is the object of the function currently being pointed to.
function fun(){
    
    
	console.log(arguments);
	console.log(arguments instanceof Array);//false
	console.log(Array.isArray(arguments));//false
	console.log(arguments[1]);//2	
	console.log(arguments.callee);//打印出fun函数
}
fun(1,2);

Embedded object: Date object

  • Use Data object to represent time in JS
  • If you create an object directly using the constructor, it will encapsulate the time of the current code. In the following example: is let d = new Date()the execution time
let d = new Date();
console.log(d);//打印出当前时间
  • Create a specified time object: you need to pass a string representing the time as a parameter in the constructorlet d2 = new Data('12/03/2016 11:10:30')
  • Date format: month/day/year hour:minute:second

method:

  • getDate(): Get the current date object is a few days (1-31), a certain day of the month
  • getDay(): Returns the day of the week (0-6) from the Date object, 0 means Sunday
  • getMonth(): Get the month (0-11) of the current time object starting from 0, 0 means January, if you want to convert normally, you need to add one
  • getFullYear(): Get the four-digit year of the current event object
  • getTime(): Get the timestamp of the current object. The timestamp refers to the number of milliseconds it takes from 0:00:00 on January 1, 1970, Greenwich Mean Time to the current time (1 second is equal to 1000 milliseconds). In order to unify the time unit of the computer, the bottom layer of the computer uses timestamps when saving time.
  • Get the current timestamp:time = Date.now()

Application:
Use timestamps to test the performance of code execution

//获取当前的时间戳
let start = Date.now();
for(let i=0;i<100;i++){
    
    
	console.log(i);
}
let end = Date.now();
console.log("执行了"+(end - start)+'毫秒');

Math

  • Math is different from other objects. It is not a constructor. It belongs to a tool class and does not need to create objects. It encapsulates properties and methods related to mathematical operations.
  • Math.PI means pi
  • Math.abs() can be used to calculate the absolute value of a numberconsole.log(Math.abs(-1)) //1
  • Math.ceil() can round up a number, and the decimal place will be automatically increased as long as it has a valueconsole.log(Math.ceil(1.001)) //2
  • Math.floor() can round down a number, and the decimal place will be droppedconsole.log(Math.floor(1.99)) //1
  • Math.round() can round a number to an integerconsole.log(Math.round(1.4)) //1
  • Math.random() can be used to generate a random number between 0-1, 0 and 1 will not appear; if you want to generate a random number from 0-10 console.log(Math.random()*10), if you want to generate an integerconsole.log(Math.round(Math.random()*10))
  • Generate a random number between xyMath.round(Math.random()*(y-x)+x)
  • Math.max() can get the maximum value among multiple numbers. Math.max(10,34,56,44);
  • Math.min() can get the minimum value among multiple numbers. Math.min(10,34,56,44);
  • Math.pow(x,y) returns x raised to the power of y. Math.pow(12,3);
  • Math.sqrt(x) performs square root operation on x

Packaging

Three wrapper classes are provided for us in JS, through which the data of the basic data type can be converted into an object
String(): the basic number type string can be converted into a String object
number(): the basic data type can be converted The number of the data type is converted into a Number object
Boolean(): the basic data type can be converted into a Boolean object

Create an object of type Number

let num = new Number(3);
console.log(num)//3
console.log(typeof num)//object对象类型

Since it is an object, you can add properties to it

num.hello = 'weewrqr';
console.log(num.hello);//weewrqr

When using a wrapper class to create two objects, the two objects are not equal

let num1 = new Number(3);
let num2 = new Number(3);
console.log(num1 == num2);//false

Reason: Two objects are compared, and the comparison is the memory address
. Note: Objects of basic data types will not be used in practical applications. If objects of basic data types are used, unexpected results may be brought about when doing some comparisons

let b = new Boolean(false);
if(b){
    
    
	alert('我运行了')
}

Result: The 'I ran' popup still pops up. Because b is an object, it has a value when it is defined

Usage of wrapper classes:

Generally speaking, methods and properties can only be added to objects, not to basic data types, but no error will be reported in the following cases

let s = 123;
s = s.toString();
console.log(s);//123
console.log(typeof s);//string

In the above example, the basic data type not only calls the toString() method, but also successfully converts the number type to the string type. This is because when we call properties and methods for some basic data type values, the browser will temporarily use the wrapper The class converts it into an object, then calls the properties and methods of the object, and converts it into a basic data type after the call

let s = 123;
s = s.toString();
s.hello = '你好';
console.log(s.hello);//undefined

In the above example, undefined is printed out; the object converted by the browser temporarily using the wrapper class is a temporary object. When adding the hello attribute to s, it temporarily converts s into an object, and adds the attribute to the object. After the attribute is added, The object is destroyed. When printing s.hello, it will read the hello attribute in the basic data type s, and the basic type cannot save attributes, so it is necessary to temporarily convert s to a string object, and then read the hello attribute, but the s before conversion does not have The property is therefore undefined. So: every call, every conversion, destroy after conversion

string method

(Mainly refers to the method in the String object)
The underlying string is stored in the form of a character array, for example: 'hello' is saved in the form of ['h', 'e', ​​'l', 'l' ,'o']; thus:let str = 'hello'; console.log(str.length)//5;console.log(str[1];//e)

charAt()

  • Can return the character at the specified position in the string
  • Get the specified character according to the index
let str = 'hello atguigu'
let result = str.charAt(6);
console.log(result);//A

charCodeAt()

  • Get the character encoding (Unicode encoding) of the character at the specified position
let str = 'hello atguigu'
let result = str.charCodeAt(6);
console.log(result);//97

fromCharCodeAt()

  • Characters can be obtained according to the character encoding;
  • Use a character object to call this method
let result = String.fromCharCode(97);
console.log(result);//a

concat()

  • Can be used to concatenate two or more strings
  • Same as +
  • It has no effect on the original string, the output str is still hello atguigu
let str = 'hello atguigu'
let result = str.concat('你好','再见')
console.log(result);//hello atguigu你好再见

indexof()

  • This method can retrieve whether a string contains the specified content
  • If the content is contained in the string, the index of its first occurrence is returned.
  • Returns -1 if the specified content is not found
  • A second parameter can be specified which specifies where to start looking
let str = 'hello atguigu';
let result1 = str.indexOf('a');
console.log(result1);//6
let result2 = str.indexOf('a',1)//6

lastIndexOf()

  • The usage of this method is the same as indexOf, the difference is that indexOf() searches from front to back, while lastIndexOf() searches from back to front
  • You can also specify where to start looking
let str = 'hello atguigu';
let result1 = str.lastIndexOf('o');
console.log(result1);//4
let result2 = str.indexOf('a',4)//o

slice()

  • The specified content can be intercepted from the specified string
  • The source string will not be affected, but the intercepted content will be returned
  • Parameters: first: the index of the start position (including the start position); second: the index of the end position (excluding the end position)
  • If the second parameter is omitted, all subsequent
  • You can also pass a negative number as a parameter. If it is negative, it will be calculated from the back. -1 means the end to the last one, excluding the last one, so there is no k
let str = 'abcdefghijk';
let result = str.slice(1,4)
console.log(result);//bcd
let result1 = str.slice(1)
console.log(result1);//bcdefghijk
let result2 = str.slice(1,-1);
console.log(result2);//bcdefghij

substring()

  • Can be used to intercept a string, similar to slice
  • Parameters: first: the index of the start interception position (including the start position) second: the index of the end position (not including the end position)
  • The difference from splice is that this method does not accept negative values ​​as parameters. If a negative value is passed, 0 is used by default.
  • The positions of the parameters are automatically adjusted, and if the second parameter is smaller than the first, the positions are automatically exchanged
  • str.substring(3,-1)==str.substring(3,0)==str.substring(0,3); so it is abc
let str = 'abcdefghijk';
let result1 = str.substring(0,2);
console.log(result1)//ab
let result2 = str.substring(3,-1);//abc
console.log(result2)

substr()

  • used to intercept the string
  • Parameters: the first one: the index of the starting position of the interception; the second one: the length of the interception
let str = 'abcdefghijk';
let result1 = str.substr(3,2);
console.log(result1)//de

split()

  • You can split a string into an array
  • Parameter: A string is required as a parameter, and the array will be split according to the string
  • If an empty string is passed as a parameter, the array will be split according to the string
let str = 'abc,def,ghi,jk';
let result = str.split(',');
console.log(result[0]);
let str1 = 'abcdefghijk';
let result1 = str1.split('');
console.log(result1);// ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']

toUpperCase()

  • Can convert a string to uppercase and return
  • will not affect the original variable

toLowerCase()

  • Can convert a string to lowercase and return
  • will not affect the original variable

regular expression

Regular expressions are used to define rules for some strings:

  • The computer can check whether a string conforms to the rules according to the regular expression, and extract the content of the string that conforms to the rules

Create a regular expression object:

  • Syntax: var variable = new RegExp('regular expression', 'matching pattern');
  • Use typeof to check the regular object and return object
  • A matching pattern can be passed as the second parameter in the constructor. Can be: i ignore case g global match pattern

Regular expression method:

  • test();
  • Use this method to check whether a string matches the rules of a regular expression
  • let reg = new RegExp('a') is used to check whether a string contains lowercase a
let reg = new RegExp('a','i');
let str = 'a';
let result = reg.test(str);
console.log(result);//true

Use literals to create regular expressions

  • Syntax: let variable = /regular expression/matching pattern
let reg = /a/i;
let str = 'a';
let result = reg.test(str);
console.log(result);//true

Create a regular expression to check whether there is a or b in a string: use | to mean or

let reg = /a|b/;
console.log(reg.test('bcd'))//true

Create a regular expression to check whether there are letters in a string: the content in [] is also an or relationship, [ab]==a|b. [az] any lowercase letter; [AZ] any uppercase letter; [Az] any letter

let reg = /[a-z]/;
console.log(reg.test('bcd'))//true

Create a regular expression to check whether a string contains abc or adc or aec

let reg = /a[bde]c/;
console.log(reg.test('aec'))//true

[^ ] except; [^ab] except ab; [^0-9] except numbers

strings and regular expressions

split()

  • You can split a string into an array
  • The method can pass a regular expression as a parameter, so the method will split the string according to the regular expression
  • This method does not specify a global match in time, and it will also split all

Requirement: Create string splitting based on any letter

let str = '1a2b3c4d5e6f7g8h9i';
let result = str.split(/[A-z]/)
console.log(result);//['1', '2', '3', '4', '5', '6', '7', '8', '9', '']

search()

  • Whether the search string contains the specified content
  • If the specified content is found, the index of the first occurrence will be returned, if not, -1 will be returned;
  • Can accept a regular expression as a parameter, and then retrieve the string according to the regular expression
  • Only the first one will be found, even if global matching is set, it will not work

Requirement: Whether the search string contains abc

let str = 'hello abc hello abc';
let result1 = str.search('abc');
console.log(result1)//6
let result2 = str.search('abcd');
console.log(result2)//-1

Requirement: Whether the search string contains abc or aec or afc

let str = 'hello abc hello aec afc';
let result1 = str.search(/a[bef]c/);
console.log(result1)//6

match()

  • According to the regular expression, the qualified content can be extracted from a string
  • By default, our match will only find the first content that meets the requirements, and stop searching after finding it. We can set the regular expression as a global matching mode, so that all content will be matched.
  • Multiple expressions can be set for a regular expression, and the order does not matter /[Az]/ig == /[Az]/gi
  • match() will encapsulate the matched content into an array and return it, even if only one result is queried

Requirement: Find all letters in a string

let str = '1a2b3c4d5e6f7g8h9i';
let result = str.match(/[A-z]/g);
let result2 = str.match(/[A-z]/ig);//即全局匹配又忽略大小写
console.log(result);//['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

replace()

  • Can replace the specified content in the string with new content
  • Parameters: 1 content to be replaced, can accept a regular expression as parameter 2 new content
  • By default only the first
let str = '1a2a3a4a5e6f7A8B9C';
let result1 = str.replace('a','@_@');
console.log(result1);//1@_@2a3a4a5e6f7A8B9C
let result2 = str.replace(/[a-z]/gi,'@_@');
console.log(result2);//1@_@2@_@3@_@4@_@5@_@6@_@7@_@8@_@9@_@
let result3 = str.replace(/[a-z]/gi,'');
console.log(result3);//123456789

regular expression syntax

quantifier:

  • Quantifiers can be used to set the number of occurrences of a content
  • {n} occurs exactly n times
  • The quantifier only works on the content before it /(ab{3})/: look for abbb, if you want to find continuous ababab, then /(ab){3}/
  • /ab{1,3}c/ means to find abc, abbc, abbbc. b appears one to three times
  • /ab{3,}c/ means that b can appear three times or more
  • {m,n} appears mn times
  • {m,} occurs more than m times
  • + at least one, equivalent to {1,}
  • *0 or more, equivalent to {0,}
  • ? 0 or one, equivalent to {0,1}
  • ^ indicates the beginning
  • $ means end
  • . represents any character
  • Use \ as an escape character in a regular expression, . means .; \ means \

Requirement: Create a regular expression to check whether aaa is contained in a string (/aaa/ == /a{3}/)

let reg = /aaa/;
console.log(reg.test('aaabs'))//true
let reg1 = /a{3}/;
console.log(reg1.test('aaabs'))//true

Requirement: Check if a string starts with a

let reg = /^a/ //匹配开头的a
let reg1 = /a$/ //匹配结尾的a
let reg2 = /^a$/ //只能有一个a
let reg3 = /^|a$/ //以a开头或者以a结尾
console.log(reg.test('abc'))//true
console.log(reg1.test('abc'))//false
console.log(reg2.test('abc'))//false

Requirement: Create a regular expression to check whether a string is a legal mobile phone number. Mobile phone number rules: 11 digits; the first digit starts with 1; the second digit is any number from 3 to 9; any number after three digits is 9

let phoneStr = '13454563656';
let phoneReg = /^1[3-9][0-9]{9}$/
console.log(phoneReg.test(phoneStr));//true

Requirement: Check whether the string contains .

let reg =/./;
let reg1 = /\./;
console.log(reg.test('s'))//true
console.log(reg1.test('s'))//false

Requirement: Check if the string contains \

let reg1 = /\\/;
console.log(reg1.test('s\\'))//true

Guess you like

Origin blog.csdn.net/weixin_48242257/article/details/121147092