Summary of some common methods of JavaScript array Array

  • 2021-12-04 09:31:50
  • OfStack

Directory 1. How to create arrays in JavaScript 2. Overview of array methods 3. Detailed explanation of the method 1.join()
2.pop()
3.shift()
4. push () 5. unshift () 6. concat () 7. slice () 8. sort () 9. reverse () 10. toString () 11. splice () 12. valueOf () 13. indexOf () 14. lastIndexOf () 15. forEach () 16. map () 17. filter () 18. every () 19. some () 20. reduce () 21. reduceRight () 22. findIndex () Summary

1. How to create arrays in 1. JavaScript

(1) Using the Array constructor:


var arr1 = new Array(); // Create 1 An empty array 
var arr2 = new Array(10); //  Create 1 Contains 20 Array of items 
var arr3 = new Array("zs","ls","ww"); //  Create 1 Contains 3 An array of strings 

(2) Use array literal notation:


var arr4 = []; // Create 1 An empty array 
var arr5 = [10]; //  Create 1 Contains 1 Array of items 
var arr6 = ["zs","ls","ww"]; //  Create 1 Contains 3 An array of strings 

2. Overview of array methods

方法名 功能 原数组是否改变
join() 使用分隔符,将数组转为字符串并返回 n
pop() 删除最后1位,并返回删除的数据 y
shift() 删除第1位,并返回删除的数据 y
push 在最后新增1个或多个数据,返回长度 y
unshift() 在第1位新增1或多个数据,返回长度 y
concat() 合并数组,并返回合并之后的数据 n
slice() 截取指定位置的数组,并返回 n
sort() 排序(字符规则),返回结果 y
reverse() 反转数组,返回结果 y
toString() 直接转为字符串,并返回 n
splice() 删除指定位置,并替换,返回删除的数据 y
valueOf() 返回数组对象的原始值 n
indexOf() 查询并返回数据的索引 n
lastIndexOf() 反向查询并返回数据的索引 n
forEach() 参数为回调函数,会遍历数组所有的项,回调函数接受3个参数,分别为value,index,self;forEach没有返回值 n
map() 同forEach,同时回调函数返回数据,组成新数组由map返回 n
filter() 同forEach,同时回调函数返回布尔值,为true的数据组成新数组由filter返回 n
every() 同forEach,同时回调函数返回布尔值,全部为true,由every返回true n
some() 同forEach,同时回调函数返回布尔值,只要由1个为true,由some返回true n
reduce() 归并,同forEach,迭代数组的所有项,并构建1个最终值,由reduce返回 n
reduceRight() 反向归并,同forEach,迭代数组的所有项,并构建1个最终值,由reduceRight返回 n
findIndex()

找到数组中第1个符合条件的元素的下标并不再遍历

n

3. Detailed explanation of the method

1.join()

Function: Places all the elements in the array into a string according to the specified delimiter and returns this string.

Parameters: join (str); Parameter is optional, and the default is "," sign, with the passed-in character as the separator.


    var arr = [1,2,3];
    console.log(arr.join());         //1,2,3
    console.log(arr.join("-"));      //1-2-3

The join () method can be used to repeat strings. You only need to pass in the string and the number of repetitions, and you can return the repeated string. The function is as follows:


function repeatString(str, n) {
return new Array(n + 1).join(str);
}
console.log(repeatString("abc", 3)); // abcabcabc
console.log(repeatString("Hi", 5)); // HiHiHiHiHi

2.pop()

pop (): Removes the last item at the end of the array, reduces the length value of the array, and returns the removed item


ar arr = [1,2,3];
console.log(arr.pop());     //3
console.log(arr);           //[1,2]--- Original array change 

3.shift()

Function: The method is used to delete and return the first element of the array.


var arr = [1,2,3]
console.log(arr.shift());       //1
console.log(arr);               //[2,3]--- Original array change 

4.push()

Function: Adds 1 or more elements to the end of the array and returns the new length.


var arr = [1,2,3];
console.log(arr.push("hello"));  //4
console.log(arr);                //[1,2,3,"hello"]--- Original array change 
console.log(arr.push("a","b"));  //6
console.log(arr);                //[1,2,3,"hello","a","b"]--- Original array change 

5.unshift()

Function: Adds 1 or more elements to the beginning of the array and returns the new length.


var arr = [1,2,3];
console.log(arr.unshift("hello"));  //4
console.log(arr);                   //["hello",1,2,3]--- Original array change 
console.log(arr.unshift("a","b"));  //6
console.log(arr);                   //["a","b","hello",1,2,3]--- Original array change 

6.concat()

Function: Adds parameters to the original array. This method first creates a copy of the current array, then adds the received parameters to the end of this copy, and finally returns the newly built array. Without passing parameters to the concat () method, it simply copies the current array and returns a copy.


const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = arr1.concat(arr2);
console.log(arr3);  //[1,2,3,4,5,6]

7.slice()

Feature: Returns a new array of items from the original array between the specified start subscript and the end subscript.

The slice () method can take 1 or two arguments, that is, the start and end positions of the item to be returned. With only 1 parameter, the slice () method returns all entries from the position specified by that parameter to the end of the current array. If you have two parameters, the method returns the item between the start and end positions--but does not include the item at the end position.


var arr = [1,3,5,7,9,11];
var arrCopy1 = arr.slice(1);
var arrCopy2 = arr.slice(1,4);
var arrCopy3 = arr.slice(1,-2);
var arrCopy4 = arr.slice(-4,-1);
console.log(arr); //[1, 3, 5, 7, 9, 11]( The original array remains unchanged )
console.log(arrCopy1); //[3, 5, 7, 9, 11]
console.log(arrCopy2); //[3, 5, 7]
console.log(arrCopy3); //[3, 5, 7]
console.log(arrCopy4); //[5, 7, 9]

8.sort()

Function: Sort the elements in the array, and the default is ascending.


var arr4 = []; // Create 1 An empty array 
var arr5 = [10]; //  Create 1 Contains 1 Array of items 
var arr6 = ["zs","ls","ww"]; //  Create 1 Contains 3 An array of strings 
0

9.reverse()

Function: Reverse the order of array items.


var arr = [13, 24, 51, 3];
console.log(arr.reverse()); //[3, 51, 24, 13]
console.log(arr); //[3, 51, 24, 13]( Original array change )

10.toString()

Function: Convert to string, similar to join () without parameters. This method is automatically invoked when data is implicitly typed or, if called manually, converted directly to a string.


var arr = [1,2,3];
console.log(arr.toString());     //1,2,3
console.log(arr);                //[1,2,3]--- The original array has not changed 

11.splice()

Features: Very powerful array method, it has many uses, can achieve delete, insert and replace.

Delete: You can delete any number of items by specifying 2 parameters: the location of the first item to delete and the number of items to delete. For example, splice (0, 2) deletes the first two items in the array.

Insert: You can insert any number of items into a specified position by providing only three parameters: the starting position, 0 (number of items to delete), and the items to insert. For example, splice (2, 0, 4, 6) inserts 4 and 6 starting at position 2 of the current array.

Replacement: You can insert any number of items into a specified location and delete any number of items at the same time by specifying three parameters: the starting location, the number of items to delete, and any number of items to insert. The number of items inserted does not have to be equal to the number of items deleted. For example, splice (2, 1, 4, 6) deletes the entry at Position 2 of the current array, and then inserts 4 and 6 from Position 2.

The splice () method always returns an array containing items deleted from the original array, or an empty array if no items are deleted.


var arr4 = []; // Create 1 An empty array 
var arr5 = [10]; //  Create 1 Contains 1 Array of items 
var arr6 = ["zs","ls","ww"]; //  Create 1 Contains 3 An array of strings 
3

12.valueOf()

Feature: Returns the original value of the array (1 is actually the array itself), 1 is called by js in the background, and does not appear explicitly in the code


var arr4 = []; // Create 1 An empty array 
var arr5 = [10]; //  Create 1 Contains 1 Array of items 
var arr6 = ["zs","ls","ww"]; //  Create 1 Contains 3 An array of strings 
4

13.indexOf()

Function: According to the specified data, from left to right, query the position in the array, and return-1 if the specified data does not exist. This method is a query method and will not change the array.

Parameters: indexOf (value, start); value is the data to be queried; start is optional, indicating the position where the query begins. When start is negative, it is counted forward from the end of the array; If the query does not find the existence of value, the method returns-1


var arr4 = []; // Create 1 An empty array 
var arr5 = [10]; //  Create 1 Contains 1 Array of items 
var arr6 = ["zs","ls","ww"]; //  Create 1 Contains 3 An array of strings 
5

14.lastIndexOf()

Function: According to the specified data, from right to left, query the position in the array, if there is no specified data, return-1. This method is a query method and will not change the array.

Parameters: lastIndexOf (value, start); value is the data to be queried; start is optional, indicating the position where the query begins. When start is negative, it is counted forward from the end of the array; If the query does not find the existence of value, the method returns-1


var arr4 = []; // Create 1 An empty array 
var arr5 = [10]; //  Create 1 Contains 1 Array of items 
var arr6 = ["zs","ls","ww"]; //  Create 1 Contains 3 An array of strings 
6

15.forEach()

Function: Loop through the array and run the given function for every 1 item in the array. This method has no return value.

Parameters: are function type, default to pass parameters, parameters are: traversal of the array content; The corresponding array index of the array itself.


var arr = [1, 2, 3, 4, 5];
arr.forEach(function(x, index, a){
console.log(x + '|' + index + '|' + (a === arr));
});
//  The output is: 
// 1|0|true
// 2|1|true
// 3|2|true
// 4|3|true
// 5|4|true

16.map()

Function: Run the given function for every 1 item in the array, and return the array composed of the results of each function call.

Use map if you want every value in the array to change


 let arr = [10, 30, 50, 60, 120, 230, 340, 450]
        let newArr = arr.map(n => {
            return n * 2
        })
        console.log(newArr);

17.filter()

Function: Filter, every 1 item in the array runs the given function, and returns the array that meets the filtering conditions.


var arr4 = []; // Create 1 An empty array 
var arr5 = [10]; //  Create 1 Contains 1 Array of items 
var arr6 = ["zs","ls","ww"]; //  Create 1 Contains 3 An array of strings 
9

18.every()

Function: Judge whether every item in the array meets the conditions. Only when all items meet the conditions will true be returned.


var arr = [1, 2, 3, 4, 5];
var arr2 = arr.every(function(x) {
return x < 10;
}); 
console.log(arr2); //true
var arr3 = arr.every(function(x) {
return x < 3;
}); 
console.log(arr3); // false

19.some()

Function: Judge whether there are items that meet the conditions in the array. As long as there is one item that meets the conditions, it will return true.


var arr = [1, 2, 3, 4, 5];
var arr2 = arr.some(function(x) {
return x < 3;
}); 
console.log(arr2); //true
var arr3 = arr.some(function(x) {
return x < 1;
}); 
console.log(arr3); // false

20.reduce()

Function: Start with the first item of the array, iterate through all the items of the array, and then build a final returned value.

Parameters:

The first parameter is: accumulator is the current aggregate value,

The second parameter is: current is the current element when the array loops

The third parameter is: index is the index value of the array element

The fourth parameter is: Array is the array itself

int: It is the initial value of accumulator and can be set by itself

1 The first two parameters are commonly used, but the latter two parameters are not commonly used. The common use scenario is the summation of arrays


 //  Action : Summarize all the contents in the array     To pass at least two values 
        let arr = [10, 30, 50, 60, 120, 230, 340, 450]
        let newArr = arr.reduce((pre, n) => {
            return pre + n
        }, 0)
        console.log(newArr);

21.reduceRight()

Features: (Similar to reduce) Start with the last item of the array, walk forward one by one to bit 1, iterate over all the items of the array, and then build a final returned value.

Parameters: Same as reduce.


var arr = [1,2,3,4,5];
var sum = arr.reduceRight(function(pre, cur, index, array){
return pre + cur;
},10);
console.log(sum); //25

22.findIndex()

Function: Returns the index of the first element in the array that satisfies the provided test function. If not, it returns-1.


let arr = [10, 2, 9, 17, 22];
let index = arr.findIndex((item) => item > 13)
console.log(index);  // 3

Summarize


Related articles: