array
Create array
Create an array with new
var arr1 = new Array();//An empty array was created
Creating arrays with array literals
var arr2 = [];//An empty array was created var arr3 = [1,'2','kalise',true];
Because the second is simple, the second is usually used
Accessing array elements
var arr3 = [1,'2','kalise',true]; console.log(arr3); console.log(arr3[2]);//kalise
The index number still starts at 0
Traversal can use the for loop, omitted
Length of array: array name length
var arr3 = [1,'2','kalise',true]; console.log(arr3.length);//4
Case: array maximum
Find the maximum value in the array [2,6,1,77,52,25,7,88,72,43,56]:
var arr = [2,6,77,52,25,7,88,72,43,56]; var max=0; for(var i=0;i<arr.length;i++){ max>arr[i] ? true:max=arr[i]; } console.log(max);
New array element
1. Modify the length: increase the length, and the unassigned part is undefined; Reducing length will discard the extra elements;
2. Modify array index:
var arr1 = [1,2]; arr1.length=3; console.log(arr1[2]);//undefined var arr2 = [3,4]; arr2[2]=5; console.log(arr2);//[3,4,5] length:3
Assigning a value to an undefined array element is to add an element; Assigning a value to a defined element is an override
Cases: filtering arrays
Requirements: select the elements greater than or equal to 10 in the array [2,0,6,1,77,10,52,20,25,7] and put them into the new array.
Method 1: define a variable j
var arr=[2,0,6,1,77,10,52,20,25,7]; var arrNew=[]; var j=0; for(var i=0;i<arr.length;i++){ /* if(arr[i]>=10){ arrNew[j]=arr[i]; j++; } */ arr[i]>=10 ? arrNew[j++]=arr[i]:true; } console.log(arrNew);
Method 2: use arrnew length
var arr=[2,0,6,1,77,10,52,20,25,7]; var arrNew=[]; for(var i=0;i<arr.length;i++){ arr[i]>=10 ? arrNew[arrNew.length]=arr[i]:true; } console.log(arrNew);
Delete the specified element of the array (array de duplication)
Requirement: remove 0 from array [2,0,6,1,77,0,52,0,25,7] to form a new array without 0.
var arr=[2,0,6,1,77,0,52,0,25,7]; var arrNew=[]; for(var i=0;i<arr.length;i++){ arr[i]!=0 ? arrNew[arrNew.length]=arr[i]:true; } arr.length=arrNew.length; for(var i=0;i<arr.length;i++){ arr[i]=arrNew[i]; } console.log(arr);
Flip array
var arr=[2,0,6,1,77,0,52,0,25,7]; var arrNew=[]; for(var i=0;i<arr.length;i++){ arrNew[arr.length-1-i]=arr[i]; } /*for(var i=arr.length-1;i>=0;i--){ arrNew[arrNew.length]=arr[i]; }*/ console.log(arrNew);
Bubble sorting
Suppose an array has n numbers, and it is required to be arranged from small to large:
understand:
From left to right, every two adjacent numbers, starting from the first two numbers, are compared to the right in turn, and the larger one each time is placed on the right until the last two numbers, so as to determine that the largest number is on the right, so far it is a round; The number determined in the previous round will no longer participate in the comparison; This cycle n-1 times to determine the number of n-1, and the last number must be the smallest.
Determine i: just confirm the number of n-1. i starts from 0, so i < arr.length-1
Determine J: the number of determined numbers before comparison is I, and arr[j] and arr[j+1] are compared. J also starts from 0, so j + 1 < arr.length-i
var arr=[4,5,1,3,2]; for(var i=0;i<arr.length-1;i++){ for(var j=0 ;j<arr.length-i-1;j++){ if(arr[j]>arr[j+1]){ var temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } console.log(arr);
The blue box indicates the two numbers to be compared; Red indicates the results after comparison; The orange box represents the number determined after the loop, and the pink box represents the array index number
I also wrote a sort myself. I thought it was bubble sort, but the algorithm is different. Let's put it here first:
var arr=[4,5,1,3,2]; for(var i=0;i<arr.length;i++){ for(var j=i+1;j<arr.length;j++){ if(arr[i]>arr[j]){ var temp=arr[i] arr[i]=arr[j]; arr[j]=temp; } } } console.log(arr);
function
function functionname() { // Execute code }
Functions with parameters
function getSum(num1,num2){ console.log(num1 + num2); } //1. Normal output getSum(1,2);//3 //If the number of arguments > the number of formal parameters, the number of formal parameters will be obtained, that is, take 1 and 2 and discard 3 getSum(1,2,3);//3 //The number of arguments < the number of formal parameters. Formal parameters without received values are undefined by default getSum(1);//NaN
Function with return value
function myFunction() { var x=5; return x; }
You can also use the return statement when you just want to exit the function.
function myFunction(a,b) { if (a>b) { return; } x=a+b }
Case: use the function to find the maximum value in any array.
function getMax(arr){ var max=arr[0]; for(var i=1;i<arr.length;i++){ max=max>arr[i] ? max:arr[i]; } return max; } var arr1=[54,46,73,28,91]; console.log(getMax(arr1));
About return:
1. The statements after return will not be executed;
2.return can only return one result; returrn num1,num2; Such returns only num2;
If you want to return multiple values, you can use an array or wrap it into an object;
3. If the function does not return, it returns undefined;
About the difference between break, continue and return:
break: ends the current loop body;
Continue: skip this cycle and continue to execute the next cycle;
Return: you can not only exit the loop, but also return the value, and end the code in the current function body
Job:
Write a function, and the user can enter a number to judge whether it is a prime number (prime number, which can only be divided by 1 and itself), and return the result:
function judgePrinum(num){ var temp=0; for(var i=2;i<=num&&temp<=1;i++){ num%i==0 ? temp++:1; } return temp==1 ? true:false; } var num=prompt('Please enter:'); alert(judgePrinum(num));
arguments
In the function, when we are not sure how many parameters are passed, we can get them with arguments.
In JS, arguments is actually a built-in object of the current function.
All functions have a built-in arguments object in which all arguments passed are stored.
function sum(){ console.log(arguments); console.log(arguments.length); console.log(arguments[2]); var n=0; for(var i=0; i<arguments.length; i++){ n += arguments[i]; } return n; } console.log(sum(1,2,3));
arguments is displayed as a pseudo array that can be traversed. Pseudo arrays have the following characteristics:
- With length attribute;
- Store data by index;
- push,pop and other methods without array
Case: use the function to find the maximum value of any number:
function getMax(){ var max=arguments[0]; for(var i=1;i<arguments.length;i++){ if(max<arguments[i]){ max=arguments[i]; } } return max; } console.log(getMax(32,41,26,55,18));
Case: flip any array by function encapsulation:
function turnArr(arr){ var newArr=[]; var j=0; for(var i=arr.length-1;i>=0;i--){ arr[j++]=arr[i]; } return newArr; } var arr1=[1,2,3,4,5,6]; console.log(turnArr(arr1));
Case: bubble sorting of function encapsulation:
function sort(arr){ for(var i=0;i<arr.length-1;i++){ for(var j=0;j<arr.length-i-1;j++){ if(arr[j]>arr[j+1]){ var temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } return arr; } var arr=[4,1,5,8,3,2,9,7,6]; console.log(sort(arr));
There are many cases, so I won't write them
Two ways to declare functions
//Using function keywords to customize functions (named functions) function fn(){ //sentence } //Function expression (anonymous function) var fun=function(str){ console.log(str); }; fun('Can pass parameters'); //(1) fun is a variable name, not a function name //(2) The declaration method of function expression is similar to that of variable declaration, except that the value is stored in variable and the function is stored in function expression //(3) Function expressions can also pass parameters
Scope
Global scope and local scope (function scope), local variable and global variable definitions are consistent with C/C + +.
About block level scopes:
(1) Block level scope: the area between curly braces such as if {}, for {};
(2) There is no block level scope in js at this stage, that is, the variables defined in if {} can also be used outside if;
(3) js is a new block level scope in es6
Note: the variables used for undefined direct assignment are regarded as global variables
In terms of execution efficiency, global variables and local variables:
(1) Global variables are destroyed only when the browser is closed, which takes up more memory
(2) Local variables will be destroyed when our program is executed, which saves memory
Scope chain
The internal function accesses the variables of the external function and uses the chain search method to determine the value. This structure is called the scope chain.... (principle of proximity)
var num=10; function fn(){ var num=20; function fun(){ console.log(num); } fun(); } fn();
When fun() looks for num, it will first look for it from the external function fn() of the upper layer, find num=20 and return; If there is no num in FN (), the global num=10 will be found in the upper layer and returned.
Case: what is the result?
function f1(){ var num=123; function f2(){ console.log(num); } f2(); } var num=456; f1();
closure
What is a closure? Advantages and disadvantages of closures
Pre analysis
Introduction 1: Operation
console.log(num);
Because num is not defined, an error will be reported; But if:
console.log(num); var num=10;
The output is: undefined... why
Introduction 2:
fn(); function fn(){ console.log(11); }
Can output 11; If it is:
fun(); var fun=function(){ console.log(22); }
The result will report an error!...???
The JS engine runs JS in two steps: pre parsing code execution
What is pre parsing?
The js engine will promote all var and function s in js to the front of the current scope
Pre parsing is divided into variable pre parsing (variable promotion) and function pre parsing (function promotion)
(1) Variable promotion is to promote all variable declarations to the front of the current scope without promoting the assignment operation
(2) Function promotion is to promote all function declarations to the front of the current scope without executing functions
Case: what is the output?
var num=10; function fn(){ console.log(num); var num = 20; console.log(num); } fn();
The above code is equivalent to
var num; function fn(){ var num; console.log(num); num = 20; console.log(num); } num=10; fn();
Therefore, the output results are undefined and 20;
Case: what is the output?
f1(); console.log(c); console.log(b); console.log(a); function f1(){ var a=b=c=9;//Equivalent to var a=9;b=9;c=9; b and C have no var declaration when the global variable //Collective declaration var a=9,b=9,c=9; console.log(a); console.log(b); console.log(c); }
amount to
function f1(){ var a; a=b=c=9; console.log(a); console.log(b); console.log(c); } f1(); console.log(c); console.log(b); console.log(a);
The output result is 5 9 and error reports;
object
create object
Create objects with object literals:
var obj={ uname:'Zhang Sanfeng', age:18, sex:'male', sayHi:function(){ console.log('Hi~'); } } console.log(obj.uname); console.log(obj['age']); obj.sayHi();
Functions in objects, called methods, pass through objects Method name ().
Create an object using new Object:
var obj=new Object();//An empty object was created obj.uname='Zhang Sanfeng'; obj.age=18; obj.sex='male'; obj.sayHi=function(){ console.log('Hi~'); } console.log(obj.uname); console.log(obj['age']); obj.sayHi();
Constructor
Because we create one object at a time, there are a lot of the same properties and methods... We use the method of function to repeat the same code, and we call this function constructor. This function is different. It encapsulates not ordinary code, but objects.
The constructor is to abstract some of the same properties and methods in our object and encapsulate them into the function.
Constructors are similar to class es in C/C + + and Java
Create objects using constructors:
function Constructor name(){ this.attribute = value; this.method = function(){} } new Constructor name();
The function name of the constructor is capitalized; The constructor does not need return to return the result
function Star(uname,age,sex){ this.name=uname; this.age=age; this.sex=sex; this.sing=function(song){ console.log(song); } } var ldh = new Star('Lau Andy',18,'male');//The calling function returns an object console.log(ldh['name']); ldh.sing('Ice rain'); var zxy = new Star('Xue You Zhang',19,'male'); console.log(zxy.name); console.log(zxy.age); zxy.sing('Li Xianglan');
Calling the constructor must use new. As long as new Star() calls the function, an object is created
Four things new will do during execution:
- Create a new empty object in memory
- Let this point to the new object
- Execute the code in the constructor to add properties and methods to the new object
- Return this new object (so return is not required in the constructor)
The for... in statement traverses the object
var obj = { name : 'kalise', age : 18, sex : 'male' } for(var k in obj){ console.log(k);//Output variable k and get the attribute name console.log(obj[k]);//Output obj[k] and get the attribute value }
Job:
- Create a computer object with color, weight, brand and model. You can watch movies, listen to music, play games and code.
- Create a button object that contains width, height, background color and click behavior.
- Create a car object with weight, color and brand. It can carry people, pull goods and farm.
- Write a function to reverse any array.
- Write a function to sort the number array.
Group project:
Make a simple calculator:
Built in object
- JS objects are divided into three types: custom objects, built-in objects and browser objects
- Built in objects are the built-in objects of JS language. These objects are used by developers and provide some common or most basic and necessary functions (properties and methods)
- The biggest advantage of built-in objects is to help us develop quickly
- JavaScript provides several built-in objects: Math, Date, Array, String, etc
Learning by looking up documents
To learn how to use a built-in object, just learn how to use its common members. We can learn by querying documents and MDN.
MDN: https://developer.mozilla.org/zh-CN/
You can enter a function / method to find a purpose, or you can enter a function / method to find a function / method
Math object
User manual for Math built-in objects
console.log(Math.PI); console.log(Math.max(1,22,44)); console.log(Math.abs(-1));//absolute value console.log(Math.abs('-1'));//Implicit conversion console.log(Math.floor(1.9));//Round down (small) console.log(Math.ceil(2.1));//Round up (large) console.log(Math.round(1.4));//rounding console.log(Math.round(1.5)); //Math.round() all other numbers are rounded, but. 5 is special. Take the larger one console.log(Math.round(-1.1));//-1 console.log(Math.round(-1.5));//This result is - 1 because - 1 > - 2
Random number method:
Math.random() Small details:
Math. The random() function returns a floating-point number, which is a pseudo-random number in the range [0,1]. This method does not follow parameters
If you need integers or have other requirements, you can find them from the link above.
For example, we want to get a random integer between two integers, which contains two integers:
function getRandom(min,max){ return Math.floor(Math.random()*(max - min + 1)) + min; } console.log(getRandom(1,10));
Case: number guessing game
The program randomly generates a number between 1 and 100, and allows the user to enter a number
- If it is greater than this number, it will prompt that the number is large and continue to guess;
- If it is less than this number, it will prompt that the number is small and continue to guess;
- If it is equal to this number, you will be prompted to guess correctly and end the program.
- Only 10 chances
function getRandom(min,max){ return Math.floor(Math.random()*(max - min + 1)) + min; } var result = getRandom(1,100); // console.log(result); var num; var i=10; var numTop=100,end=1; do { num = prompt('Please enter a number:('+end+'~'+numTop+')'); i--; if(num>result){ numTop=num; alert('unfortunately╮(╯﹏╰)╭The number is big\n You have'+i+'Second chance'); }else if(num==result){ alert('Congratulations! You guessed right!\n‧★,:*:‧\( ̄▽ ̄)/‧:*‧°★* \n The result is'+result);break; }else{ end=num; alert('unfortunately╮(╯﹏╰)╭The number is small\n You have'+i+'Second chance'); } }while(i>0) if(i==0){ alert('Unfortunately, the opportunity has run out~The game is over\n╮(╯﹏╰)╭'); }
Date Date object
User manual for Date object
The only way to create a new Date object is through the new operator, for example: var now = new Date(); Similarly:
var arr = new Array();//Created an array object var obj = new Object();//An object instance was created
If you call it as a regular function (that is, without the new operator), you will return a string instead of a Date object.
console.log(Date());//Thu Jan 20 2022 10:59:50 GMT+0 800 (China standard time)
Parameters of Date:
//Use Date. If there is no parameter, return the current time of the current system var date = new Date(); console.log(date); //The common writing method of parameters is numeric 2022,01,20 or string '2022-1-20 10:59:50' var date1 = new Date(2022,01,20); console.log(date1);//February is returned instead of January var date2 = new Date('2022-1-20 10:59:50');//Most commonly used console.log(date2);
Date object is different from Math object. Date() is a constructor, so we need to instantiate it before using it
Date format
Mm / DD / yy
var date = new Date(); console.log(date.getFullYear());//Returns the year 2022 of the current date console.log(date.getMonth()+1);//The month returned in the month is 1 month smaller. Remember to add 1 month to the month console.log(date.getDate());//What number is returned console.log(date.getDay());//Monday returns 1, Saturday returns 6, and Sunday returns 0 //Let's write a Thursday, January 20, 2022 var year = date.getFullYear(); var month = date.getMonth()+1; var dates = date.getDate(); var arr = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; var day = date.getDay(); console.log('Today is:'+year+'year'+month+'month'+dates+'day '+arr[day]);
Hour, minute and second
var date = new Date(); console.log(date.getHours());//Time console.log(date.getMinutes());//branch console.log(date.getSeconds());//second //It is required to encapsulate a function to return the current time, minute and second format 08:08:08 function getTime(){ var time = new Date(); var h = time.getHours(); h = h<10 ? '0'+h : h; var m = time.getMinutes(); m = m<10 ? '0'+m : m; var s = time.getSeconds(); s = s<10 ? '0'+s : s; return h + ':' + m + ':' + s; } console.log(getTime());
Combine the two:
var date = new Date(); var year = date.getFullYear(); var month = date.getMonth()+1; var dates = date.getDate(); var arr = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; var day = date.getDay(); //It is required to encapsulate a function to return the current time, minute and second format 08:08:08 function getTime(time){ var h = time.getHours(); h = h<10 ? '0'+h : h; var m = time.getMinutes(); m = m<10 ? '0'+m : m; var s = time.getSeconds(); s = s<10 ? '0'+s : s; return h + ':' + m + ':' + s; } console.log('Now Beijing time '+year+'year'+month+'month'+dates+'day '+getTime(date)+' '+arr[day]);
Gets the total number of milliseconds (timestamp) of the date
The Date object is based on January 1, 1970 (world standard time) Milliseconds since
We usually use the total number of milliseconds to calculate time because it is more accurate
The total number of milliseconds to obtain Date refers to the number of milliseconds since January 1, 1970
Four methods:
var date = new Date(); //1. Use valueOf() getTime() console.log(date.valueOf());//Is the total number of milliseconds from 1970.1.1 console.log(date.getTime()); //2. Simple writing method (the most commonly used writing method) var date1 = +new Date();//The total number of milliseconds is returned console.log(date1); //3.H5 NEW console.log(Date.now());
Case: countdown effect
Case study:
- Core algorithm: the input time minus the current time is the remaining time, that is, the countdown, but you can't directly subtract with ten seconds. For example, if you subtract 25 points from 05 points, the result will be negative
- Do it with a timestamp. The total number of milliseconds of the user input time minus the total number of milliseconds of the current time is the number of milliseconds of the remaining time
- Convert the total number of milliseconds of the remaining time into days, hours, minutes and seconds (the timestamp is converted to tens of seconds)
The conversion formula is as follows
D = parseInt (total seconds / 60 / 60 / 24)// Calculation days
H = parseInt (total seconds / 60 / 60% 24)// Calculate hours
M = parseInt (total seconds / 60% 60)// Calculate minutes
S = parseInt (total seconds% 60)// Calculate current seconds
The teacher's code in class is:
function countDown(time){//'2022-1-21 14:00:00' var nowTime = +new Date(); var endTime = +new Date(time); var times=Math.floor((endTime-nowTime)/1000);//Total countdown seconds if(times<=0){ return; } var d =Math.floor(times/3600/24); d=d>10 ? d:'0'+d; var h =Math.floor(times/3600%24); h=h>10 ? h:'0'+h; var m =Math.floor(times/60%60); m=m>10 ? m:'0'+m; var s =Math.floor(times%60); s=s>10 ? s:'0'+s; return d+'day '+h+':'+m+':'+s; } console.log(countDown('2022-1-21 14:00:00'));
In this way, the remaining time can only be displayed once, and the countdown cannot be automatically counted down; Leave an article for future study: [JavaScript] minute and second countdown timer
Array object
new Array() is actually the second way to create an array:
var arr1 = new Array();//Create an empty array var arr2 = new Array(2);//An array with length 2 is created, and the array element is empty var arr3 = new Array(2,3);//Equivalent to arr3=[2,3]
Detect whether it is an array
When the formal parameter is an array and the argument is not an array, a bug will occur, so it is necessary to check whether the passed parameter is an array.
Note case:
var arr = []; var obj = {}; //The first method: instanceof operator console.log(arr instanceof Array);//Return true console.log(obj instanceof Array);//Return false //The second method: array Isarray (parameter); H5 new method console.log(Array.isArray(arr));//true console.log(Array.isArray(obj));//false
Adding and deleting array elements
Method name | explain | Return value |
---|---|---|
Push (parameter 1...) | Add one or more elements to the end of the array | Returns the new length |
pop() | Delete the last element of the array and reduce the length of the array by 1 | Returns the value of the last element it deleted |
Unshift (parameter 1...) | Add one or more elements to the beginning of the array | Returns the new length |
shift() | Delete the first element of the array and reduce the length of the array by 1 | Returns the value of the first element deleted |
//push() var arr = [1,2,3]; console.log(arr.push(4,'kalise'));//5 console.log(arr); //unshift() console.log(arr.unshift('good')); console.log(arr); //pop() console.log(arr.pop()); console.log(arr); //shift() console.log(arr.shift()); console.log(arr);
Cases: filtering arrays
There is an array [1500120020021001800] containing wages. It is required to delete those whose wages exceed 2000 in the array and put the rest into the new array:
var arr = [1500,1200,2000,2100,1800]; var arrNew = []; for(var i=0;i<arr.length;i++){ if(arr[i]<2000){ //arrNew[arrNew.length]=arr[i]; arrNew.push(arr[i]); } }
Array sorting:
Method name | explain | Modify original array |
---|---|---|
reverse() | Invert the order of the elements in the array | The original array will be changed and a new array will be returned |
sort() | Sort the elements of the array | The original array will be changed and a new array will be returned |
Note arr.sort(function(a,b){return b-a;}); How to write. more
//Flip array var arr = ['red','blue','yellow']; arr.reverse(); console.log(arr); //Array sort (bubble sort) var arr1 = [12,4,7,34,26,10,8]; arr1.sort(function(a,b){ //return a-b;// Ascending sort return b-a;//Descending sort }); console.log(arr1);
Get array element index
Method name | explain | Return value |
---|---|---|
indexOf() | Finds the first index of a given element in an array | If it exists, the index number is returned; If it does not exist, - 1 is returned |
lastIndexOf() | Finds the last index of the given element in the array | If it exists, the index number is returned; If it does not exist, - 1 is returned |
var arr = ['red','green','blue','pink','blue','black'];//There are two blue console.log(arr.lastIndexOf('blue')); console.log(arr.indexOf('blue')); console.log(arr.indexOf('yellow'));
Array de duplication
There is an array ['c', 'a', 'z', 'a', 'x', 'a', 'x', 'c', 'b') that requires the removal of duplicate elements.
var arr = ['c','a','z','a','x','a','x','c','b']; function unique(arr){ var arrNew = []; for(var i=0;i<arr.length;i++){ //if(arrNew.indexOf(arr[i])===-1) if(i==arr.indexOf(arr[i])){ arrNew.push(arr[i]); } } return arrNew; } console.log(unique(arr));
Convert array to string
Method name | explain | Return value |
---|---|---|
toString() | The array is converted to a string, with each item separated by a comma | A string |
join('separator ') | The array is converted to a string, and each item is separated by the input separator | A string |
//toString() var arr = [1,2,3]; console.log(arr.toString());//1,2,3 //Join (separator) var arr1 = ['green','blue','pink']; console.log(arr1.join());//green,blue,pink console.log(arrr1.join('-'));//green-blue-pink
After class inquiry:
Method name | explain | Return value |
---|---|---|
concat() | Connecting two or more arrays does not affect the original array | Returns a new array |
slice() | Array interception slice(begin,end) | Returns a new array of intercepted items |
splice() | Delete the splice from the array (starting from the first few, the number to be deleted). Note that this will affect the original array | Returns a new array of deleted items |
slice() and slice() have basically the same purpose. We suggest focusing on slice(). Link guide: concat();slice();splice()
String object
var str = 'andy'; console.log(str.length);//4
Thinking: only objects have attributes and methods, and only complex data types have attributes and methods. Why do simple data types have length attributes?
Basic package type
Is to wrap simple data types into complex data types. In this way, the basic data type has properties and methods.
When you write str.length, you execute:
//(1) Generate temporary variables and wrap simple data types into complex data types var temp = new String('andy'); //(2) Give the value of the temporary variable to str str = temp; //(3) Destroy temporary variables temp = null;
JS provides three special reference types: String, Number, and Boolean.
Immutability of string
When var str = 'andy', we open up a space in memory to store 'andy', and then declare a variable str, which is used to point to the space where 'andy' is stored; When str = 'city', we will open up a space in memory to store 'city', and let str point to the space of 'city' again. The space of 'andy' has not been destroyed or changed.
Because of the immutability of strings, do not splice a large number of strings.
Return position according to character
All methods of the string will not modify the string itself (the string is immutable), and a new string will be returned after the operation is completed.
Method name | explain |
---|---|
indexOf('character to find ', starting position) | Returns the position of the specified content in the original string. If it is not found, it returns - 1. The starting position is the index index number |
lastIndexOf() | Look back and forward, only the first one that matches |
var str = 'The spring breeze of reform is blowing all over the ground, and spring is coming'; console.log(str.indexOf('spring'));//2 console.log(str.indexOf('spring',3));//8 console.log(str.lastIndexOf('spring'));//8
Case: return string position
Find the location and number of occurrences of all o in the string 'abcoefoxyozzopp'
Teacher's example:
var str = "abcoefoxyozzopp" ; var index = str.indexOf('o'); var num = 0; while ( index !==-1) { console.log(index); num++ ; index = str.indexOf('o', index + 1); } console.log( 'o The number of occurrences is:'+ num);
my
var str = 'abcoefoxyozzopp'; function seekO(){ var temp = -1; var arr = []; do{ temp=str.indexOf('o',temp+1); if(temp!=-1){ arr.push(temp); } }while(temp!=-1) return arr; } var arr=seekO(); console.log('A total of'+arr.length+'Times, respectively'+arr.join(',')+'Office.');
Returns characters based on position
Method name | explain | use |
---|---|---|
charAt(index) | Returns the character at the specified position (the index number of the index symbol string) | str.charAt(0) |
charCodeAt(index) | Gets the ASCII code (index index number) at the specified location | str.charCodeAt(0) |
str[index] | Gets the character at the specified position | HTML5, IE8 + support and charAt() equivalent |
// 1. charAt(index) returns characters according to position var str = 'andy'; console.log(str.charAt(3)); //Traverse all characters for(var i=0;i<str.length;i++){ console.log(str.charAt(i)); } // 2. charCodeAt(index) returns the character ASCII value of the corresponding index number. Purpose: to judge which key the user pressed console.log(str.charCodeAt(0)); // 97 // 3. str[index] H5 NEW console.log(str[0]); // a
Case: count the maximum characters and times in the string
Understand the following code before making a case:
var o = { age:18 } if(o['age']){ console.log('have age');//output }else{ console.log('No, age'); } if(o['sex']){ console.log('have sex'); }else{ console.log('No, sex');//output }
o ['age'] returns 18; o ['sex'] returns undefined
After understanding, do the following cases:
Judge the character that appears the most times in a string 'abcoefoxyozzopp', and count its times. (key cases)
Core algorithm:
- Use charAt() to traverse the string
- Store each character to the object. If the object does not have this attribute, it will be 1. If it exists, it will be + 1
- Traverse the object to get the maximum value and the character
var str = 'abcoefoxyozzopp'; var o = {}; for(var i = 0;i<str.length;i++){ //str.charAt(i) for each character: 'a','b','c' if(o[str.charAt(i)]){ o[str.charAt(i)]++; }else{ o[str.charAt(i)]=1; } } //ergodic var max = 0; var ch = ''; for(var k in o){ //K gets the attribute name; o[k] gets the attribute value if(o[k]>max){ max = o[k]; ch = k; } } console.log('The characters that appear most are'+ch+',A total of'+max+'second'); /*var maxchar=str.charAt(0); for(var k in o){ // console.log(k+':'+o[k]); maxchar=o[maxchar]>o[k] ? maxchar:k; } console.log('The most frequent character is' + maxchar + ', with a total of' + o[maxchar] + 'times'); */
String operation method
Method name | effect | explain |
---|---|---|
concat(str1,str2,str3...) | connect | Used to connect two or more strings. Splice string, equivalent to +. |
substr(start,length) | intercept | Starting from the start position (index number), length is the number of characters taken (remember this) |
slice(start,end) | intercept | Start from the start position and intercept to the end position, but end cannot (both of them are index numbers) |
substring(start,end) | intercept | Start from the start position and intercept to the end position. The end can't get basically the same as slice, but it doesn't accept negative values |
replace('a','b') | replace | A is the character to be replaced and b is the character to be replaced. Only the first character can be replaced, and a cycle is required for all replacement |
split('separator ') | transformation | Convert the string to an array, STR = 'red,pink,blue'; str.split(’,’);// [‘red’,‘pink’,‘blue’] |
After class query: toUpperCase() / / convert to uppercase; toLowerCase() / / convert to lowercase
Job:
Given a string, such as "abaasdffggghjkkglddssss344343", the problem is as follows:
1. Length of string
2. Take out the characters in the specified position, such as 0, 3, 5, 9, etc
3. Find out whether the specified character exists in the above string, such as I, C, B, etc
4. Replace the specified characters, such as g with 22, ss with b, etc
5. Intercept the string from the specified start position to the end position, for example: get the string of 1-5
6. Find out the character with the most occurrences and the number of occurrences in the above string
Simple data type and complex data type
Simple data type = basic data type = value type: string,number,boolean,undefined,null
Complex data type = reference type: object, array
null in the simple data type returns an empty object object
Heap and stack
Stack space allocation difference:
1. Stack (operating system): the operating system automatically allocates and releases the parameter values of the stored function and the values of local variables. Its operation mode is similar to the stack in the data structure;
Simple data types are stored on the stack
2. Heap (operating system): it stores complex types (objects), which are generally allocated and released by the programmer. If the programmer does not release them, they are collected by the garbage collection mechanism.
Complex data types are stored in the heap
Simple data type: declare age, open up space in the stack to store 18, and age points to it;
Complex data type: declare arr, open up space in the heap to store the value of the array [1,2,3], open up space in the stack to store the address of the array, arr points to the address, and the address points to the value of the array;
var age = 18; VaR and arr = [1,2,3];
Note: there is no stack concept in JavaScript. The stack method can make it easier for you to understand some execution methods of code and facilitate learning other languages in the future
Simple data type parameters
To put it simply, formal parameters are a new space opened up by functions and have no effect on external arguments. Similar to that local variable.
Complex data type parameter transfer
--------------------------------------------------------------------------Split line---------------------------------------------------------------------------
finish
These two are my self-study notes following the video of station B. the original video BV is BV1ux411d75J