JS study notes-array

1. Array

  1. Array is also an object
  2. Its function is similar to ordinary objects, and it is also used to store some values.
  3. The difference is that ordinary objects use strings as attribute names, while arrays use numbers as index operation elements.
  4. Index: an integer starting from 0
  5. The storage performance of arrays is better than that of ordinary objects. In development, we often use arrays to store some data.

Two, create an array object

  1. When using typeof to check an array, return object
var  arr=new Array();

7. Add elements to the array

Syntax: array [index] = value

var  arr=new Array();
arr[0]=10;

8. Read the elements in the array

Syntax: Array [index]
If reading a non-existent index, return undefined

9. Get the length of the array, length

Syntax: array.length
(1) For a continuous array, use length to get the length of the array (number of elements);
(2) For a non-contiguous array, use length to get the largest index of the array +1
(3 ) Try not to create non-contiguous arrays

10. Modify length

(1) If the modified length is greater than the original length, the extra part will be vacated
(2) If it is less than the original length, the extra element will be deleted. So you can delete some elements by modifying the length.

11. Add an element to the last position of the array

Syntax: array[array.length]=value

Three, array literal

1. Use literals to create arrays

Syntax: var arr =[]
2. When using a literal to create an array, you can specify the elements in the array when creating it.

var arr=[1,2,3,4,5]//索引为1的值是1....

2. When using the constructor to create an array

You can also add elements at the same time, pass the elements to be added as the parameters of the constructor, and separate the elements with commas.

var arr2=new Array(10,20,30)

3. Create an array with only one element 10

var arr=[10]

4. Create an array of length 10

arr2=new Array(10)

5. The elements in the array can be any data type

Can be an object

var arr=[10,20]
var obj={
    
    name:"小per"};
arr[arr.length]=obj;
console.log(arr);
//输出结果:10,20,{name:"小per"}
console.log(arr[2].name);//小per

Can also be a function

arr=[function(){
    
    alert(1)}];

Arrays can also be placed in arrays, two-dimensional arrays

arr=[[1,2],[2,3]]

Fourth, the array method

1. push() method

(1) This method can add one or more elements to the end of the array and return the new length of the array. The elements to be added can be passed as the method parameters, so that these elements will be automatically added to the end of the array.
Syntax: array.push("value", "value");
(2) This method will return the new length of the array as the return value.

2. pop() method

(1) This method can delete the last element of the array and return the deleted element as the return value.
Syntax: array.pop()

3. unshift() method

(1) Add one or more elements to the beginning of the array and return the new array length
syntax: array.unshift("value")
(2) After adding elements to the front, the indexes of other elements will be adjusted in turn

4.shift() method

(1) You can delete the first element of the array, and return the deleted element as the return value.
Syntax: array.shift()

5.slice() method

(1) The specified element can be extracted from the array
(2) This method does not change the original array, but encapsulates the intercepted elements into a new array and returns.
(3) Parameters:
1. The index of the position where the interception starts, including the beginning index
. 2. The index of the position where the interception ends, excluding the end index
. 3. The second parameter can be left blank. At this time, the interception from the beginning index and the subsequent All elements

var arr=["孙悟空","猪八戒","沙和尚","唐僧","白龙马"];
arr.slice(0,2);//截取索引0-2的元素

(4) The index can pass a negative value, if a negative value is passed, it will be calculated from back to front, -1 is the first to last, -2 is the second to last

6.splice() method

(1) Can be used to delete the specified element in the array
(2) Using splice() will affect the original array, delete the specified element from the original array, and return the deleted element as the return value
(3) Parameters: splice (first parameter, second parameter, added element 1, added element 2)
1. The index of the starting position of the interception, including the starting index
2. The number of deletions
third and later: you can pass some new elements , These elements will be automatically inserted in front of the delete start position index

7.concat() method

(1) concat() can concatenate two or more arrays and return a new array. You can also pass elements
(2) Syntax: array 1.concat (array 2);
(3) This method will not affect the original array, but the returned result is a concatenated array.

8.join() method

(1) This method can convert the array into a string
(2) This method does not affect the original array, but returns the converted string as the result. The type of the returned result is a string
(3) You can specify a string as a parameter in join(), and this string will become the connector of the elements in the array. If it is not written, the default connector is a comma.

9.reverse() method

(1) This method is used to invert the array (the front side goes to the back, the back side goes to the front)
(2) This method will directly modify the original array

10.sort() method

(1) The elements of the array can be sorted
(2) The original array will be affected, and the default sort is Unicode.
(3) Even for an array of pure numbers, when using sort() to sort, it will be sorted according to unicode encoding. So when sorting numbers, you may get wrong results.
(4) You can specify the sorting rules yourself. We can add a callback function to sort() to specify the sorting rules.
The callback function needs to define two formal parameters, and the browser will use the elements in the array as actual parameters to call the callback function.
It is uncertain which element to call, but it must be in the array that a must be before b.
(5) The browser will determine the order of the elements according to the return value of the callback function. If a value greater than 0 is returned, the elements will exchange positions. If a value less than 0 is returned, the element position is unchanged. If it returns a 0, the two elements are considered equal, and the positions are not exchanged.
(6) If you need to sort in ascending order, return ab, and if you need to sort in descending order, return ba.

arr[5,4];
arr.sort(function(a,b){
    
    
  //前边的大
 /* if(a>b){
    return 1;
}else if(a<b){
   return -1;
}else{
   return 0;
}*/
//升序排列
return a-b;
//降序排序
return b-a;

})

Five, array traversal

  1. The so-called traversal of the array is to take out all the elements in the array
for(var i=0;i<arr.length;i++){
    
    
    console.log(arr[i]);
}

Six, sample questions

function Person(name,age){
    
    
							this.name=name;
							this.age=age;
							
						}
						var per=new Person("孙悟空",18);
						var per2=new Person("猪八戒",28);
						var per3=new Person("红孩儿",8);
						var per4=new Person("蜘蛛精",17);
						var per5=new Person("沙和尚",38);
						
						var perArr=[per,per2,per3,per4,per5];
						 function fun(arr){
    
    
							 //创建一个新数组
							var newArr=[];
							 for(var i=0;i<arr.length;i++){
    
    
								//判断Person的年龄是否大于等于18
								if(arr[i].age>=18){
    
    
									//将对象放入到新数组中
									newArr.push(arr[i]);
							} 
						} 
						//将新的数组返回
						return newArr;
						}
						var result=fun(perArr);
						console.log(result);
var arr=[1,2,3,2,1,3,4,2,5]
		//去除数组中重复的数字
		for(var i=0;i<arr.length;i++){
    
    
			//获取当前元素后的所有元素
			for(var j=i+1;j<arr.length;j++){
    
    
				//判断两个元素是否相等
				 if(arr[i]==arr[j]){
    
    
					 //如果相等则证明出现了重复的元素,则删除j对应的元素
					arr.splice(j,1);
					//当删除了当前j所在的元素以后,后边的会自动补位
					//此时将不会在比较这个元素,需要再比较一次j所在位置的元素
					j--;
				} 
				
			}
		}

Seven, forEach() method

  1. Generally we use the for loop to traverse the array. JS also provides us with a method to traverse the array forEach(). This method only supports browsers above IE8. IE8 and below browsers do not support this method.
  2. The forEach() method requires a function as a parameter. Functions like this, created by us but not called by us, are called callback functions.
  3. There are several elements in the array that will be executed several times. Each time it is executed, the browser will pass the traversed elements in the form of actual parameters. We can define formal parameters to read these contents.
  4. The browser will pass three parameters in the callback function:
    (1) The first parameter: the value of the element currently being traversed
    (2) The second parameter: the index of the element currently being traversed
    (3) The third parameter: The array obj being traversed
arr.forEach(function(value,index,obj){
    
    

});

Eight, call and apply methods

1. These two methods are methods of function objects and need to be called through function objects.
2. When calling the function call () and apply () will call the function execution.
3. When calling call and apply, you can specify an object as the first parameter, and this object will become this when the function is executed.

function(){
    
    
 alert(this);
}
var obj={
    
    };
fun.apply(obj);//{}
	var obj={
    
    
			name:"孙悟空",
			sayName:function(){
    
    
				alert(this.name);
							}
			};
			var obj2={
    
    
				name:"obj2",
				};
	      obj.sayName.apply(obj2);//参数是谁谁,this就是谁
  1. The call() method can pass the actual parameters once after the object. The apply() method needs to encapsulate the actual parameters into an array and pass them uniformly.
function fun(a,b){
    
    
		 console.log("a="+a);
		 console.log("b="+b);
		}
		var obj={
    
    
			name:"孙悟空",
			sayName:function(){
    
    
				alert(this.name);
							}
			};
			var obj2={
    
    
				name:"obj2",
				};
	      fun.call(obj,2,3);
	      fun.call(obj,[2,3]);

Nine, arguments

  1. When calling the function, the browser will pass in two implicit parameters every time.
    The context object of the function this
    encapsulates the object arguments of the actual parameters
  2. Arguments is an array-like object, it can also manipulate data by index, or get the length. When calling the function, the actual parameters we pass will be encapsulated and saved in arguments.
  3. Check whether arguments is an array
arguments instanceof Array;//检查arguments是否是Array类的实例
Array.isArray(arguments);
  1. The length of arguments can be used to get the length of the actual argument. There are several actual parameters, the length is how many
  2. Even if you don't define formal parameters, you can use arguments to use actual parameters, but it's more troublesome.
    arguments[0] represents the first
    argument arguments[1] represents the second argument
  3. The arguments have a callee attribute, which corresponds to a function object currently being executed.

Guess you like

Origin blog.csdn.net/weixin_45636381/article/details/113047422