SoFunction
Updated on 2025-03-09

Summary of commonly used array operation methods in JavaScript

Preface

The difference between functions and methods:

Function function: an independent function, then it is called a function.

function foo() {}

Method method: When one of our functions belongs to a certain object, we call this function the method of this object.

var obj = {
  foo: function() {}
}
()

For example, we call it a method for an array: filter.

// filter: filtervar nums = [10, 5, 11, 100, 55]
((item) => item > 10)

In the following operations on arrays, we collectively call them methods.

Common constant meanings in the article:

item: A certain item. When as an argument, iterates over each item in the array. When used as a return value, it means a certain item of data and can be of any type.

index: Subscript. When used as an argument, the item in the traversal array is subscripted in the array. When used as a return value, it means subscript.

arr: Array. When used as a return value, it means changing the array itself. When used as an argument, it means its own array.

length: array length. When used as a return value, it means the length of the array

newarr: New array. When used as a return value, it means to generate a new array.

boolean: Boolean value. When used as the method body, it is considered that the return value of the condition is a Boolean value.

num: Numeric type.

start: Array traversal start subscript (included)

end: Array traversal end subscript (not included)

Basic array traversal method

for

for(var i = 0, len = ; i < len; i++ ){
  (arr[i])
}

The for basic loop can be used to traverse arrays, strings, class arrays, DOM nodes, etc.

for of

for (var item of arr) {
  (item);
}

for of: for-of gets the value of the array. You can use break, continue, and return to interrupt the loop traversal.

for in

for (var value in arr) {
  (value); 
}

for in: It is generally used for traversal of objects, but it can also be used for arrays. When used for array traversal, for-in gets the index of the array

var arr = [10, 7, 9, 100, 11]

for (var value in arr) {
  (value); 
}
// 0 1 2 3 4

Notice:

1).index index is a string type number and cannot be directly used for geometric operations.

2).Use for in to iterate through all enumerable properties of the array, including prototypes. For example, the prototype method and name attribute of Shangli.

=function(){
    alert('myfun');
}    
var arr = [0,1,2,3];

for(var i in arr){
    (arr[i]);
}

()
/* Output result:
 0 1 2 3
 ƒ (){
     alert('myfun');
 }
 */

Basic operation methods of arrays

push: add elements at the tail

var length = (item)

The push() method is used to insert new elements into the tail of the array. The return value is the appended array length.

var nums = [10, 7, 9, 100, 11]

var length = (2)
(length) // 2

pop: Remove elements from the tail

var item = ()

The pop() method is used to delete the last element of the array and return the deleted element. No parameter, the return value is the deleted element.

var nums = [10, 7, 9, 100, 11]

var item = ()
(item) // 11

unshift: add elements to the head

var length = (item)

The unshift() method is used to insert new elements into the array header. The return value is the appended array length.

shift: header remove element

var item = ()

The shift() method is used to insert and remove elements from the head of the array. The return value is the element that was chased out.

splice: remove add replacement

var newarr = (index, howmany, item) 

The splice() method is used to delete, add and replace array elements. Returns an array of elements with deleted values.

index (required): Array index, which means that the operation is performed from the first element.

howmany (optional): Specifies how many elements to delete. If this parameter is not specified, all elements from index to the end of the original array are deleted.

item (optional): Insert elements, can be multiple. Insert from the subscript position.

var nums = [10, 7, 9, 100, 11]
var newarr= (2,2,99,77,55)

(newarr) // [9, 100]
(nums) // [10, 7, 99, 77, 55, 11]

Note: The splice() method will change the original array.

concat:Connection

newarr = (nums1, nums2)

The concat() method is used to concatenate two or more arrays.

var nums1 = [2,5,7,9]
var nums2 = [1,3,55]
var newarr = []
var newarr = (nums1, nums2)

The concat() method does not change the original array.

join: segmentation

Str = (separator)

separator: The splitter, if empty, it has been split ",".

The join() method is used to convert all elements in an array into a string.

var nums = [10, 7, 9, 100, 11]

var Str = ('x')
(Str) // 10x7x9x100x11

slice: Cut

newarr = (start, end)

Intercept the array element from the [start, end) position of the array.

The slice() method returns the selected element from an existing array.

The slice() method extracts a part of the string and returns the extracted part as a new string.

Note: The slice() method does not change the original array.

include: query

boolean = (value, start)

value (required): The element found can be a string or a numeric value.

start (optional): The location where you start searching is subscripted.

The include() method is used to determine whether a string contains the specified substring. The return value is a boolean value.

indexOf: query

index = (value, start)

value (required): The element found can be a string or a numeric value.

start (optional): The location where you start searching is subscripted.

The indexOf() method is used to determine whether a string contains the specified substring. The return value is the query subscript, and if it is query, it is -1.

The lastIndexOf() method is similar, with the return value as the last occurrence of the subscript of value.

fill: fill/replace

(value, start, end)

value (required): Used to fill the value of the array element.

start (optional): Optional start index value (included), the default value is 0.

end (optional): Optional terminate index (not included), the default value is .

Usually withnew ArrayUse with combination.

var arr = new Array(10).fill('10')
// ['10', '10', '10', '10', '10', '10', '10', '10', '10', '10']

Or used to replace the value of the element in the array.

var arr3 = [0, 1, 2, 3, 4, 5, 6]
((1, 3)); //[0, 1, 2, 1, 1, 1, 1]

Advanced array method brought in es6

Next is the higher-order array method brought in es6.

Advanced-order function: If a function receives another function as a parameter, or the function returns another function as a return value, then this function is called a higher-order function.

Advanced methods of arrays usually receive a callback function as a parameter, traverse the array in the callback, and perform operations.

Next

Write in front: The higher-order array methods introduced next, and the write methods of callback functions are all written in the way of arrow functions. Since the arrow does not have its own this pointing, we will not introduce the second parameter thisValue.

forEach: Iteration (enumeration)

((item, index, arr) => { Write the operation you want to enumerate })

The forEach method does not change the original array and does not return a value;

var nums = [10, 7, 9, 100, 11]
((item) => {
    if (item > 10) {
        (item)
    }
}) // 100, 11

forEach cannot use break to break out of loop. When using return, the effect is consistent with using continue in a for loop.

If you want to break out of the loop, you can do it by throwing an error by throwing a new Error() .

var nums = [10, 7, 9, 100, 11]
((item) => {
    if (item == 100) {
        throw new Error("miss 100")
    } else {
        (item)
    }
}) // 10 7 9 Error: miss 100

filter: filter

newarr = ((item, index, arr) => boolean)

example:

var nums = [10, 7, 9, 100, 11]
var newNums = ((item) =&gt; {
  return item % 2 === 0 // Even number})
(newNums) // [10, 100]
(nums) // [10, 5, 11, 100, 55]

The return value is the filtered new array

map:map

newarr = ((item, index, arr) => { Write the specified method body })

The map() method returns a new array composed of the return value of each element in the original array called a specified method.

var nums = [10, 7, 9, 100, 11]

var newNums = ((item) => { 
  return item * 10
})
(newNums) // [100, 50, 110, 1000, 550]
(nums) // [10, 5, 11, 100, 55]

Note: The callback function in the map method only needs to accept one parameter, which is the array element itself being traversed.

But this does not mean that map only passes one parameter to callback (it will pass 3 parameters). This thinking inertia may make us a very easy mistake.

// What does the following statement return:["1", "2", "3"].map(parseInt);
// What you may think is [1, 2, 3]// But the actual result is [1, NaN, NaN]
// () , parseInt() receives two parameters, the first is the string to be converted, and the second is the number of the binary (between 2-36). If the parameter is omitted or its value is 0, the number will be parsed on a basis of 10, exceeding the return NaN.// The callback of map will pass three parameters to it: the element currently traversing, the element index, and the original array itself.  The third parameter is ignored// So it is equivalent to execution, parseInt("1", 0), parseInt("2", 1), parseInt("3", 2),
// The correct way to write it should be:function returnInt(element){
 return parseInt(element,10);
}
 
["1", "2", "3"].map(returnInt);
// Return [1,2,3]

find: Find

item = ((item, index, arr) => { boolean })

The find() method is used to get the first element in the array that meets the specified criteria. No return undefined was found.

var family = [
  { name: 'xiaoming', age: 18 },
  { name: 'xiaocheng', age: 40 },
  { name: 'xiaoli', age: 42 }
]

var item = ((item) => {
  return  === 'xiaoming'
})
(item) // { name: 'xiaoming', age: 18 }

Note that the returned item is a shallow copy.

 = 'kkk'
(family)
/*
* {name: 'kkk', age: 18}
* {name: 'xiaocheng', age: 40}
* {name: 'xiaoli', age: 42}
*/

Here it is reflected that the result returned by the find() method is still the memory address pointed to by family.

So what is returned here is the shallow copy of the data.

findIndex: Find the subscript

index = ((item, index, arr) => { boolean })

findIndex() returns the first element position (index) of the array that meets the criteria. If no matching criteria is found, return -1.

var family = [
  { name: 'xiaoming', age: 18 },
  { name: 'xiaocheng', age: 40 },
  { name: 'xiaoli', age: 42 }
]

var index = ((item) => {
  return  === 'xiaoming'
})
(index) // 0

The above is the detailed summary of the commonly used array operation methods in JavaScript. For more information about JavaScript array operation methods, please pay attention to my other related articles!