Basic Usage of JavaScript Arrays and Functions

Table of contents

1. Array

1. The concept of array

2. Array creation

3. Array acquisition

4. Array traversal

5. Add elements to the array

Two, function

1. Function call

2. Function parameters

3. The return value of the function

4. Use of arguments


1. Array

1. The concept of array

- An array is a special kind of variable that can hold more than one value at a time.

- Any type of element can be stored in the array.

2. Array creation

- Create an array with the new keyword

var arrayName = new Array();

var arr = new Array(); // Create a new empty array "A" in uppercase.

var arr = new Array('car','truck');

- Create an array directly from an array literal.

var array-name = [item1, item2, ...];

var arr = ['car','truck'];

Note: Any data type can be stored in the array. Such as: ['Xiaoming',12,true,28.9]

3. Array acquisition

An array can access, set, and modify the corresponding array elements through the index (subscript), and the elements in the array can be obtained through the form of "array name [index]". The subscript of the array starts from 0.

// define the array

var arr= [1,2,3];

// Get the second element in the array.

alert(arr[0]); //1 

alert(arr[1]); //2

alert(arr[2]); //3

alert(arr[3]); //undefined

Note: If the array does not have an element corresponding to the index value when accessed, the resulting value is undefined

4. Array traversal

Each element in the array is accessed once, and the array can be traversed through the for loop.

var arr = ['Xiaoming','Xiaohong', 'Big Fatty'];

for(var i = 0; i < arr.length; i++){

    console.log(arr [i]);

}

- The length of length is the number of arrays, not subscripts.

- When the number of elements in our array changes, the length property changes accordingly.

- The length property of the array can be modified:

- If the set length attribute value is greater than the number of elements in the array, an empty element will appear at the end of the array, and undefined will be displayed when accessing an empty element;

- If the set length attribute value is less than the number of elements in the array, the array elements exceeding this value will be deleted.

//js

 var arr = ['Xiaoming', 'Xiaohong', 'Xiaolan', 'Big Fat'];

  arr.length = 3;

console.log(arr.length);

console.log(arr);

5. Add elements to the array

```js

  array[array.length] = newData;

```

Example:

var arr = ['Xiaoming', 'Xiaohong', 'Xiaolan', 'Big Fat'];

    arr[1] = 'Xiaoshuai';// reassignment

    arr[arr.length] = 'Xiaoshuai';//Add a new value at the end

console.log(arr);

Two, function

Function: It is **encapsulating a code block that can be called and executed repeatedly**. This code block can **reuse a large amount of code**.

// declare function

function function-name() {

    return the value to be returned;

}

//example

function sayHello(){

  console.log(“hello”);

}

- function is the keyword for declaring a function and must be lowercase

- Since functions are generally defined to achieve a certain function, we usually name the function name as a verb, such as getSum;

- The function needs to be called before it is executed, and the code block inside is not executed if it is not called.

1. Function call

  // Declare the function to calculate the sum between 1-100

  function getSum(){

    var sumNum = 0;// Prepare a variable to save the number and

    for (var i = 1; i <= 100; i++) {

      sumNum += i;// add each value to the variable

    }

    alert(sumNum);

  }

 getSum(); //Function call.


2. Function parameters

- Formal parameter: When the function is defined, it is set and passed in when receiving the call.

- Actual parameter: the actual data passed in parentheses when the function is called.

The role of parameters: Some values ​​​​can not be fixed inside the function, we can pass different values ​​into it when calling the function through parameters.

function say(mylanguage){

  console.log("Please speak" + mylanguage);

}

say("Chinese");

  ```js

  // Function declaration with parameters.

  function function name (formal parameter 1, formal parameter 2, formal parameter 3...) { // Any number of parameters can be defined, separated by commas.

    // function body

  }

  // function call with parameters

  functionName(Argument1, Argument2, Argument3...);

  ```

  1. When calling, the actual parameter value is passed to the formal parameter.

  2. Formal parameters are simply understood as: variables that do not need to be declared.

  3. Multiple parameters of actual parameters and formal parameters are separated by commas (,).

 function getSum(sum1,sum2,sum3){

 console.log(sum1);

  console.log(sum2);

   console.log(sum3);

}

 getSum(sum1,sum2,sum3);

Summarize:

- You can declare a function without parameters;

- When there are more actual parameters than formal parameters, the formal parameters only read the number of formal parameters;

- When the actual parameters are less than the formal parameters, the formal parameters are not assigned the value undefined. In order to ensure that errors are inevitable, the parameters must be consistent.

3. The return value of the function

Return value: the data represented by the function call as a whole; after the function is executed, the specified data can be returned through the return statement.

// declare function

function function-name() {

    ...

    return the value to be returned;

}

//example

function getName(){

return "Primary class 2: Zhang San";

}

var myname = getName();

console.log(myname);

- When the return statement is used, the function stops executing and returns the specified value.

- If the function does not return, the returned value is undefined

- return only returns a value, such as return 1,2. // return 2

break ,continue ,return

- break: end the current loop body (such as for, while)

- continue: Jump out of this loop and continue to execute the next loop (such as for, while)

- return : Not only can exit the loop, but also return the value in the return statement, and at the same time end the code in the current function body.

4. Use of arguments

When you are not sure how many parameters to pass, you can use arguments to get it. In JavaScript,

arguments is actually a built-in object of the current function. All functions have a built-in arguments object,

All arguments passed are stored in the arguments object. The arguments display form is a pseudo-array,

So it can be traversed. Pseudo-arrays have the following characteristics:

- Has a length property.

- Store data by index.

- Methods such as push and pop that do not have an array.

    function fn() {

            // We can iterate over the arguments as an array

            for (var i = 0; i < arguments.length; i++) {

                console.log(arguments[i]);

            }

     }

    fn(1, 2, 3);

    fn(1, 2, 3, 4, 5);

Note: Use this object inside the function, and use this object to obtain the actual parameters passed when the function is called.

- Pseudo-arrays are not real arrays.

  - Has a length property of the array.

- Stored in an indexed manner.

  - It doesn't have some methods pop() push() etc. of real arrays.

practice questions

1. Encapsulate a function to determine whether a certain value exists in an array.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script>
			var arr = ['a','s','d','f','8'];
			console.info(isInArray(arr,'8'));//循环的方式
			function isInArray(arr,value){
			    for(var i = 0; i < arr.length; i++){
			    if(value === arr[i]){
			      return "在这个数组中";
			        }
			    }
			    return "不在这个数组中";
			}
		</script>
	</body>
</html>

achieve effect

2. Pass an array to realize the function of flipping the array. 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script>
			function overturn(){
			var arr = ["a","b","c","d","e"];
			  var newarr = [];
			  for (var i=arr.length-1;i>=0;i--){
			  	newarr[newarr.length]=arr[i];
			  }
			  return newarr;
			  }
			  var newarr = overturn();
			console.log(newarr);
			
		</script>
	</body>
</html>

achieve effect

 3. Array screening, put students with passing scores (60 points) into a new array.

var score = [90,20,49,10,80,65,44,70,60];

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script>
			var score = [90,20,49,10,80,65,44,70,60];
			var newscore = [];
			for (var i=0;i<score.length;i++) {
				if(score[i]>=60){
				newscore[newscore.length]=score[i];
			  }
			}
			console.log(newscore);
		</script>
	</body>
</html>

achieve effect

Guess you like

Origin blog.csdn.net/qq_65715980/article/details/125546247