Javascript arrays and functions

1. Array (Array)

1.1 The reason why we need to use an array to store a lot of data is like putting a lot of data into a box, and we can take it out when we use it.

2. How to create an array

2.1 Using the Array constructor

	<script type="text/javascript">
		//through the Array() constructor
		var arr1=new Array();//Create an empty array
		var arr2=new Array(10);//Create an array of length 20
		var arr3=new Array("姓名","casf",100);
		console.log(arr1);
		console.log(arr2);
		console.log(arr3);		
	</script>

2.2 Using array literals

	<script type="text/javascript">
		var arr1=[];//Create an empty array
		var arr2=[40,"30",true];
		console.log(arr1);		
		console.log(arr2);			
	</script>

There are two ways to define an array first

	<script type="text/javascript">
		//define an array
		var per=["Zhang","Male",18];
		console.log(per);
		var per1 = [];
		per1[0]="李";
		per1[1]="女";
		per1 [2] = 16;
		console.log(per1);		
	</script>

The data in the array is placed on the stack, the stack is first in last out

Queue is first in first out

Each array will have an index, starting from 0 is the first of the array

2.3.1 Specify the length of the array

	<script type="text/javascript">
		var arr=[123,"fdsf",324,23,324];
		arr.length=100;
		console.log(arr);
		
		var arr1=[123,"fdsf",324,23,324];		
		console.log(arr1.length);
	</script>

2.3.2 Retrieve data according to the index

	<script type="text/javascript">
		var arr=[123,"fdsf",324,23,324];
		console.log(arr);
		console.log(arr[0]);
		console.log(arr[arr.length]);//undefined because arr.length is 5 and the second index is 0 to 4
		console.log(arr[arr.length-1]);//324	
	</script>

Exercise 1: Define an array, store personal information in the array and output

	<script type="text/javascript">
		//Define an array, store personal information in the array and output
		var num=[1,2,3,4,5,6,7];
		for(var i=0;i<num.length;i++){
			var item=num[i];
			console.log(item);
		}
	</script>

Exercise 2: Traverse the array to find the even numbers

	<script type="text/javascript">
		//Define an array, store personal information in the array and output
		var num=[1,2,3,4,5,6,7];
		for(var i=0;i<num.length;i++){
			var item=num[i];
			console.log(item);
		}
	</script>

Exercise 3: Find the maximum and minimum values ​​in an array

	<script type="text/javascript">
		// find the maximum and minimum values ​​in an array
		var num=[23,45,566,768,434,234,665,4,67,-67];
		var max = num [0];
		var min=num[0];//Maximum, minimum
		var maxsy,minsy;//Maximum index, minimum index
		for(var i =1;i<num.length;i++){
			//If the element in the array is greater than the initial value we defined
			if(num[i]>max){
				//Assign this element to the maximum value and change the index
				max=num[i];
				maxsy = i;
			}
			if(num[i]<min){
				min = num [i];
				minsy = i;
			}
			
		}
		console.log(max);
		console.log(min);
		console.log(maxsy);
		console.log(minsy);
	</script>

Exercise 4: Remove the zero values ​​from the array and store them in a new array

	<script type="text/javascript">
		/ / The value of zero in the array is removed and not zero is stored in a new array
		var num=["War Three",434,44,23,0,33,5423,0,0,24,35,12,2,0,6,4,0];
		var newnum = [];
		// loop through the array
		for(var i=0;i<num.length;i++){
			if(num[i]!==0){
				newnum[newnum.length]=num[i];
			}
		}
		console.log(newnum);
	</script>

Second, the division of functions

Function with parameters according to the number of parameters

                                            no-argument function

By return value Function with return value

                                            function with no return value

Divide system functions by writing function objects

                                            custom function

3. Basic definition of function: a piece of code that completes a specific function when a function is used, that is, a code block that can be executed repeatedly, such as

Mathfloor (), Mathrandem ()

Function: Encapsulate frequently called code and call it when needed

3.1 Defining functions

function function name(parameter1, parameter2,.......){

            function body

}

Function name();

Below I will write a simplest function call

        <script type="text/javascript">
		//Define the function to output 10
		function log (){
			console.log(10);
		}
		alert(000);
		debugger;//Breakpoint
		//Call functions
		log();
	</script>

3.2 Function declaration

3.2.1 Direct function declaration method, 2, function expression declaration method, 3, using function constructor (which will be used when encapsulating the framework)

        <script type="text/javascript">
		//1, function declaration method
		function log (){
			console.log(10);
		}
		//Call functions
		log();
		//2, function expression declaration method
		var add=function(){
			console.log(1+3);
		}
		add();
		//3, use the function constructor
		var add2=new Function(console.log(5+3));
		
	</script>

3.2.2 Direct function declaration is different from expression declaration

Direct function declaration can first mention the function declaration of the current scope to the front of the entire scope, but the function expression declaration cannot.

        <script type="text/javascript">
		console.log(sum(10,20));
		//function directly declared
		function sum(num1,num2){
			return num1+num2;
		}
		
	</script>
        <script type="text/javascript">
		//Function expression declaration can not be, an error is reported
		console.log(add(20,30));
		var add=function (num1,num2){
			return num1+num2;
		}
	</script>


3.3 There are two kinds of parameters of the function (formal parameter and actual parameter) The formal parameter is for the actual position of the actual parameter

For example, a and b are formal parameters, and the value passed in when calling the function (the actual parameter) is the actual parameter,

Exercise 1: Find the sum of two numbers

        <script type="text/javascript">
		function add(a,b){
			console.log(a+b);
		}
		add(1,2);//3
	</script>

*Note: In other languages, the number of actual parameters must be the same as the number of formal parameters, and no error will be reported in js. It will correspond the actual parameters to the formal parameters one by one from front to back, and many are invalid.

Extension: find the sum of multiple numbers

        <script type="text/javascript">
		// find the sum of multiple numbers
		function sum(numArr){
			var num=0;
			for(var i=0;i<numArr.length;i++){
				num+=numArr[i];
			}
			console.log(num);
		}
		
		sum([1,2,3]);
	</script>

3.4 arguments object

Simply use the arguments object to output an array

<script type="text/javascript">
		//arguments object
		function sum(){
			console.log(arguments);//Number of output arguments
		}
		sum(1,2,3);//Output a pseudo-array that resembles an array that is not an array
	</script>

There is also a callee property in the arguments object, which is a pointer to the function that owns the arguments object and

	<script type="text/javascript">
		function showcallee() {
			var a = 'this is a';
			var b = 'this is b';
			var c = a + b;

			console.log(arguments.callee);
			return c;
		}
		showcallee();
	</script>


Use the arguments object to find the sum of multiple numbers

        <script type="text/javascript">
		//arguments object
		function sum(){
			var num=0;
			for(var i=0;i<arguments.length;i++){
				num+=arguments[i];
			}
			console.log(num);
			console.log(arguments.length);//The number of output arguments
			console.log(sum.length);//Number of output parameters
			
		}
		sum(1,2,3);//Output a pseudo-array that resembles an array that is not an array
	</script>

3.5 Function return value return

When a function is called, it usually executes from the beginning to the end of the function. If you want to end the execution of the function in advance, you can use the return statement. All statements after the return statement will not be executed. Generally, the return statement returns the result.

        <script type="text/javascript">
		function sum(){
			console.log(1);//Only output 1
			return(10);//Return the final functional function value
			console.log(2);//Will not output 2
		}
		sum();
		console.log(sum());//undefined		
	</script>

*Note: 1. If the function uses the return statement, then the value following return becomes the return value of the function

            2. If the function uses the return statement but there is no value behind it, the function returns undefined;

            3. Recommendations either always have a valid return value or do not apply

Exercise 1: Find whether a number is odd or even

<script type="text/javascript">
		//Please write whether a number is even
		function os(num){
			if(num%2===0){
				return "even";
			}
			else{
				return "odd";
			}
		}
		console.log(os(7));
	</script>

Exercise 2: Please write the Mathmin(x,y) function

        <script type="text/javascript">
		//Please write the function of Math.min(x,y)
		console.log(Math.min(1,2));
	</script>
        <script type="text/javascript">
		function min(a,b){
			if(a>b){
				return b;
				
			}
			else{
				return a;
			}
		}
		console.log(min(11,2));
	</script>

4. Anonymous functions

4.1 Used when binding events

Click anywhere to execute a click event at runtime

        <script type="text/javascript">
		document.onclick=function(){
			alert(1);
		}
	</script>

4.2 Timer

        <script type="text/javascript">
		// timer
		setInterval (function(){
			console.log(111);
		},1000);
	</script>

4.3 Self-invoking functions (closures) put anonymous functions in a closure

        <script type="text/javascript">
		(function() {
			alert("hello")
		})();
	</script>

5. Callback function

A callback function is to call a function through a function. If you pass the pointer of a function as a parameter to another function, when the pointer is used to call the function it points to, we say this is a callback function, which is generally used in recursion ( That is, calling itself).

Exercise: Make a calculator with callback functions

	<script type="text/javascript">
		// simple calculator
		function fangf(num1,num2,huidiao){
			return huidiao(num1,num2);
		}
		//add, subtract, multiply and divide methods
		function jiafa(a,b){
			return a+b;
		}
		function jianf(a,b){
			return a-b;
		}
		function chengf(a,b){
			return a*b;
		}
		function chufa(a,b){
			return a/b;
		}
		console.log(fangf(10,20,jiafa));
		console.log(fangf(10,20,jianf));
		console.log(fangf(10,20,chengf));
		console.log(fangf(10,20,chufa));
	</script>

Exercise 2: Find the nth number of fibonacci 1,1,2,3,5,8,13,21,...

	<script type="text/javascript">
		/ / Find the nth number of fibonacci
		//1,1,2,3,5,8,13,21,...
		function fang(n){
			if(n===1||n===2){
				return 1;
			}
			else{
				return fang(n-1)+fang(n-2)
			}
			
		}
		console.log(fang(8));
	</script>

Exercise 2: Add n numbers to 1+2+3+.....

	<script type="text/javascript">
		//Add n numbers to 1+2+3+.....
		function sum(n){
			if(1===n){
				return 1;
			}
			else{
				return n+sum(n-1);
			}
		}
		console.log(sum(100));
	</script>

Exercise 3: Once upon a time there was a mountain, and there was a temple in the mountain...

	<script type="text/javascript">
		//Once upon a time there was a mountain, and there was a temple in the mountain...
		var i = 100;
		function fangf(){
			i--;
			//end condition of recursion
			if(i>=10){
				console.log("There used to be a mountain, and there was a temple in the mountain"+i);
				// recursive call
				fangf();
			}
		}
		fangf();
	</script>

6. Scope of variables

6.1 Block scope

In other languages, any statement in scope belongs to a block, and all variables defined in it cannot be accessed outside the code block, but js can access

        <script type="text/javascript">
		{
			var a=1;
			
		}
		console.log(a);
	</script>

6.2 Global and local variables

	<script type="text/javascript">
 		var b=2;//global variable
 		{
 			var a=1;//global variable
 }
 function sum(){
 var c=3;//local variable
 console.log(c );
 }
 console.log(a);
 console.log(b);
 sum();
 //console.log(c); will report an error because local variables cannot be directly accessed externally
 </script>			
													
											
Exercise one:
	<script type="text/javascript">
		var color = "yellow";
		function getcolor() {
			var anothercolor = "red";

			function swapcolor() {
				var tmpcolor = color;//yellow
				color = anothercolor;//red
				anothercolor = tmpcolor;//yellow
			}
			swapcolor();
		}
		getcolor();
		console.log(color);//red
	</script>

output red

Exercise two:

	<script type="text/javascript">
		var num=10;
		fun();
		function fun(){
			console.log(num);
			var num=30;
		}//Output undefined
	</script>

First, we enter the fun() method. When num is output, a num will be defined by default, which is equivalent to the following code, so it is undefined

	<script type="text/javascript">
		var num=10;
		fun();
		function fun(){
			var num;
			console.log(num);
// var num=30;
		}//Output undefined
	</script>

Exercise three

	<script type="text/javascript">
		var a=18;
		fun();
		function fun(){
			var b=2;
			console.log(a);
			console.log(b);
			var a="123";			
		}//Output undefined and 2
	</script>

Exercise four:

<script type="text/javascript">
		fun();
		console.log(c);//output 9
		console.log(b);//output 9
		console.log(a);//Error reporting

		function fun() {
			var a = b = c = 9;
			console.log(a);//output 9
			console.log(b);//output 9
			console.log(c);//output 9
		}
	</script>




















Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325642165&siteId=291194637