1, Array creation
1. The array constructor creates an array with the keyword new
var arr=new Array();//arr=[] var arr=new Array(10); //The array length is 10 var arr=new Array (10, 20, 30, 40); //arr=[10,20,30,40]
2. Literal creation
var arr=[10,20, ,40] // [] contains the stored data
3. Create object. Create()
var arr=Object.creat(new Array()) //arr=[] var arr=Object.creat(new Array(10,20,30)) //arr=[10,20,30]
2, Read
Format: array [index], the index is calculated from 0
Length is a read-only property of an array object and represents the length of the object
var arr=['a','b','c','d']; console.log(arr[2]); // console.log(arr.length); //4
3, Traversing array elements: for
var arr=[1,2,3,4]; for (var i=0;i<arr.length;i++){ console.log(`arr[${i}]=${arr[i]}`) } //arr[0]=1 //arr[1]=2 //arr[2]=3 //arr[3]=4
4, Array length variability
var arr=[1,2];//Array with length of 2 arr [4] = 0; for (var i=0;i<arr.length;i++){ console.log(`arr[${i}]=${arr[i]}`) } console.log(arr.length) //5 //arr[0]=1 //arr[1]=2 //arr[2]=undefined //arr[3]=undefined //arr[4]=0 //If you add arr[4] directly, the length will become 5, but arr [2] and arr [3] are undefined //arr[3]=undefined
5, Techniques and methods of adding data at the end of an array
var arr=[1,2]; //Array with length of 2 arr [arr. Length] = 3; //arr[2]=3 is to add an element arr[arr.length]=4 where the subscript is 3; //arr[3]=4 add an element console.log(arr) where the subscript is 3; //[1, 2, 3, 4] //Using the characteristics of index and length difference 1
6, Array method:
1. Ordinary array method
var arr=[1,2,3,4] //1. : push (added element): add an element to the last side of the array and return the length of the new array arr.push(5); console.log(arr)//[1, 2, 3, 4, 5] //2. Unshift (added element); Adds an element to the front of the array and returns the length of the new array arr.unshift(0); console.log(arr);//[0, 1, 2, 3, 4, 5] //3,pop(); Delete the last element of the array and return the deleted element arr.pop(); console.log(arr);//[0, 1, 2, 3, 4] //4,shift(); Delete the first element of the array and return the deleted element arr.shift(); console.log(arr);//[1, 2, 3, 4] //5. Slice (start subscript, end subscript (not included)) intercepts part of the array and returns a new array var arr=[1,2,3,4,5,6]; console.log(arr.slice(1,3))// [2, 3] //6. splice (start subscript (including the position of this subscript), delete length) deletes the data specified in the middle, and then deletes the array //The length will change. If you use delete to delete an item of the array, the length of the array will not change. arr.splice(0,2); console.log(arr);//[3, 4] //7. Replace data: splice (start subscript (including the position of this subscript), delete length, replaced new data) arr.splice(0,1,4); console.log(arr);//[4, 4] //8. Insert data: splice (start subscript (including the position of this subscript), delete length (set to 0), insert new data) arr.splice(0,0,2);console.log(arr);//[2, 4, 4] //9. reverse(): flip array arr.reverse(); console.log(arr);//[4,4,2] //10. Join (specified character): add a specified character in the middle of each item of the array to concatenate the array, and the returned string is arr.join(''); console.log(arr);//244 //11. concat(): merge arrays var arr1='hello'; var arr2='world'; console.log(arr1.concat(arr2));//helloworld //12*,sort(); Array of strings arranged from small to large arr=['world','he','hello','Hello','my bad','how are you']; console.log(arr.sort()) // ["he", "hello", "world", "hello", "how are you", "I'm not good"] //When comparing strings, the first letter is used for comparison. If the first letter is the same, the second letter is used for comparison //If you need to compare the size of the number array, you need to use the callback function to customize the collation var nums =[3,100,1,2,4,200]; nums.sort(function(a,b){ return a-b;//Ascending}); console.log(nums)//[1,2,3,4,100,200]
2. Array method with parameter function
1) . detailed explanation of array sorting method sort():
arr.sort([compareFunction])
If the elements in the array are strings, the sorting is normal. If the array elements are numbers, the sorting is not the result we want;
If you want to sort the number array, you need to add a comparison function to define the sorting method:
The compareFunction function accepts two parameters and has a return value
The internal principle of sort refers to bubble sorting, compares the two parameters received by the function, and determines whether to exchange the positions of the two parameters according to the return value.
var nums =[3,100,1,2,4,200]; //Ascending order nums.sort(function(a,b){ return a-b; }); console.log(nums)//[1,2,3,4,100,200] //Descending order nums.sort(function(a,b){ return b-a; }); console.log(nums) //[200,100,4,3,2,1]
If you want to sort the attributes inside the object, we need to improve the compareFunction function to sort a certain attribute more flexibly:
var stu=[ {name:'Zhang San',age:20,score:50}, {name:'Zhang Si',age:30,score:20}, {name:'Li Si',age:15,score:45} ] //Define comparison function function compare(temp){ return function(a,b){ // Ascending order if(a[temp]>b[temp]){ // If you are simply arranging numbers, you can return a[temp]-b[temp] return 1; } if(a[temp]<b[temp]){ return -1; } //Return 0 when equal return 0; } } stu.sort(compare('score')); //Arrange stu.sort(compare('age ') in ascending order according to scores; //console.log(stu) in ascending order of age
2) Iterator method
The parameters of these methods are functions. In addition to their own incidental functions, relevant logical processing can be carried out in the incoming functions.
1. Iterator method that does not generate a new array (a new array will not be generated after running)
(1) Foreach (custom function without return value): run this custom function without return value for each item in the array. The effect is similar to that of the for loop.
var arr=[3,4,7,9]; //Pass an anonymous function to the forEach method, which can have three formal parameters //The first parameter value: receives each element of the array. / / the second parameter key: receives the subscript of the array //The third parameter, array, receives the entire array, arr arr.forEach(function (value,key,array){ console.log(value); // 3 4 7 9 console.log(key); // 0 1 2 3 console.log(array) //[3, 4, 7, 9] //We can process the internal data and output console.log(value*value) // 9 16 49 81 })
(2) reduce() evaluates an array element to a value
Syntax: arr.reduce(function(init, current element, current element subscript, this array), initial value)
init is the initial value, which is passed in later. If the initial value is passed in, the current element is the first item of the array. If no initial value is given, the first item of the array is the initial value by default, and the current element is the second item. The second item is each element of the array;
In addition to representing the initial value, the return value of the previous function execution will be passed to the first item.
The return value of reduce() is a value
arr=[2,6,4,7,9,9,3,2,1]; let result=arr.reduce(function(a,b,index,arr){ //a: The initial value and the return value of the previous function //b: For the current element, if the initial value is given: B is the first item; if the initial value is not given: B is the second item //Index: the index of the current element //arr: this array return a+b; //Return the results of the two numbers to the next a to realize accumulation },0) console.log(result) //43
(3) Every (custom function with Boolean return value): run a custom function with Boolean return value for each item in the array; After the execution of every() method, there will be a return value. If the user-defined function returns true after running each item of the array, the final result will return true. If one item is false, the final result will be false. Similar to the logical relationship "and"
var arr=[3,5,7,8,9]; //Determine whether the elements in the arr array are odd var result=arr.every(function (item,index,array){ //The first formal parameter item: receives each element of the array //The second parameter index: receives the index of the array //The third parameter, array, receives the entire array, arr if(item%2==1){ console.log(item+'It's an odd number') return true; }else{ console.log(item+'Not odd') return false; } }) //Run result / / 3 is odd / / 5 is odd / / 7 is odd / / 8 is not odd /*false We can see that inside the every method, the user-defined function processes each item of the array. If the processing result is true, the next item will continue to be processed. When false occurs, it will end directly. The subsequent items will not be processed, and false will be returned directly */ console.log(result) //false console.log(item + 'is odd')
(4) Some (custom function with Boolean return value): execute the passed in custom parameter with Boolean return value for each item of the array. The some() method is similar to the every method. There will be a return value after execution. The return value depends on the return value of the custom function after running each item of the array. If each item returns false, If one item is true, the result is true, which is similar to the logical relationship "or".
var arr=[3,5,7,8,10]; //Judge whether the elements in the ARR array contain an even number var result=arr.some(function (item,index,array) {/ / the first formal parameter item: receives each element of the array //The second parameter index: receives the index of the array //The third parameter, array, receives the entire array, arr if(item%2==1){ console.log(item+'It's an odd number') return false; } if(item%2==0){ console.log(item+'It's an even number') return true; } }) //Run result / / 3 is odd / / 5 is odd / / 7 is odd /*8 It is an even number. We can see that inside the some method, the user-defined function processes each item of the array. If the return result is false, it will continue to execute the next item. When the return result is true, it will end directly, and the subsequent elements will not be judged. The final result is true */ console.log(result) //true
2. Iterator method to generate a new array (a new array will be generated after running)
(1) Map (user-defined function of return value): This user-defined function is executed for each item of the array. After the map method is executed, the return value processed by the user-defined function will be put into the new array.
var arr=[1,2,3,4,5,6,7]; //Multiply all the odd numbers of this array by 2 var result=arr.map(function (item,index,array){ //The first formal parameter item: receives each element of the array //The second parameter index: receives the index of the array //The third parameter, array, receives the entire array, arr if(item%2==1){ return item*2; }else if(item%2==0){ return item; } }) console.log(result) //Operation results /*[2, 2, 6, 4, 10, 6, 14] You can see that result is a new array generated after the map method is executed result The element of the array is the return value of each item of the element group processed by the user-defined function*/
(2)filter (user defined function with Boolean return value): execute this user-defined function with Boolean return value for each item of the array. Unlike the every and some methods, it will not stop execution because of the return value, but execute each element of the array. During execution, if the processing result of the user-defined function is true, put this element into the new array. If If the processing result is false, it will not be put in.
var arr=['hello',2,'Xiao Ming',4,'world','study',7]; //Filter out all the strings of this array var result=arr.filter(function (item,index,array){ //The first formal parameter item: receives each element of the array //The second parameter index: receives the index of the array //The third parameter, array, receives the entire array, arr if(typeof item=='string'){ return true; }else{ return false; } }) console.log(result) //Operation results /*["hello", "Xiao Ming "," world "," study "] can see, filter The function puts all the elements that return true after being processed by the custom function into a new array*/
3. Method to determine whether it is an array
var num=1; console.log(typeof num); //number var str=''; console.log(typeof str) //string var arr=[]; console.log(typeof arr) //object var obj={}; console.log(typeof(obj)) //object /*Because arrays are reference type variables and special objects, when we use typeof to judge the type of an array, we will get an object. So how to judge whether arr is an array or an object? We can use the method provided with the array: array. Isarray (array to be judged) */ console.log(Array.isArray(arr)); //true arr is an array console.log(Array.isArray(obj)); //false obj is not an array
4, Class array
Using the access property when the key of the object is of type number, create an object similar to the access mode of array.
var obj={ 1:'Zhu', 2:18 } //We know that if the key of an object is a number, we will not be able to access it by using object variables // console.log(obj.1) / / an error will be reported console.log(obj['1']) //Zhu console.log(obj[1]) //Zhu
It can be seen that when the key of an object is of type number, we can use obj [num] to access the value. Therefore, we can define an object (class array) in this way. In this way, we can access the elements of the object like accessing an array.
var obj = { 0: 'apple', 1: 'orange', 2: 'pear', 3: 'banner', //Define a function to get the length of this class array get length() { var i = 0; for (var key in this) { i++; } return i - 1; // return Object.keys(this).length-1 //Object.keys(this) extracts all the keys of this object and puts them into an array // Object. Keys (this). If the length is equal to 5, the getter function will be included } } console.log(obj[1],obj[2]) //orange pear console.log(obj.length) //4 var arr = ['apple', 'orange', 'pear', 'banner']; console.log(arr[1],arr[2]) //orange pear console.log(arr.length) //4