Several methods of javaScript array traversal and the processing of sparse arrays

brief introduction

   array traversal method is also called array iterator method. Iterator is a software design pattern in programming. In js, we can use it to traverse the array without paying attention to the details of its internal implementation.
   the following traversal methods will not affect the original array, that is, if we assign values to its children internally, we will not modify the value of the original array. Note: This article does not include the general for loop, for of loop, while and other methods to traverse the array.

Method introduction

1.forEach() method

   the forEach (parameter 1, parameter 2) method itself can receive two parameters. The first parameter is a function, and each element in the array will call this function once (except sparse array). Generally speaking, we will only pass in the first parameter (and it is a required item). Other parameters are not introduced here. The parameter transfer of the following other methods is the same as that of forEach().
   in the following methods, the function passed in as a parameter also has parameter values, which are the value of array element, the index of array element and the array itself. Namely:

myArray.forEach(
    function (The value of the array element, the index of the array element, and the array itself) {

    }
)

Supplement: function (a) {return a+3} is an anonymous function without function name, which can be written in the form of arrow function
a => a+3

Example:

	let myArray = [1,2,3];
	// Num = > {} arrow function, equivalent to an anonymous function
	// function(num) { num = num * 3 }
	myArray.forEach(num => {
	    num = num * 3;
	});
	console.log(myArray)	//The print result is [1, 2, 3]

    the forEach() method has no return value, and there is no break statement that can terminate the iteration like an ordinary for loop. As mentioned above, the changes we made to num here will not be changed to the myArray array.

2.map() method

The difference between   map() and forEach() methods is that the first parameter function of map() method will receive the elements of each array and return a value. The return value of the whole map() method is the array composed of the return value of this function.
  example:

let myArray = [1,2,3]
let result = myArray.map(num => {
    num *= 3
    return num
});
console.log(result,"\n Original array",myArray)
//	The print result is
//	[ 3, 6, 9 ] 
//	Original array [1, 2, 3]

3.filter()

The   filter() method also has a return value, but it expects the return value of the parameter function to be a boolean type, that is, it expects the parameter function to be an assertion function. Its return value is an array of elements in myArray that meet the conditions.
Example:

let myArray = [1,2,3]
let result = myArray.filter(num => {
    num *= 3
    return num > 5
});
console.log(result)
//[ 2, 3 ]

4. Some very useful methods

  • find() and findIndex()
       these two methods are similar to filter(), but they will stop the iteration when they find the first value that meets the condition. The find() method will return the value of the element, and the findIndex() method will return the index of the element in the array. Example:
let myArray = [1,2,3]
let result = myArray.find(num => {
    num *= 3
    return num > 5
});
console.log(result) // Print value: 2
let myArray = [1,2,3]
let result = myArray.findIndex(num => {
    num *= 3
    return num > 5
});
console.log(result) // Print value: 1
  • every() and some()
        the return values of every() and some() functions are boolean types, and an assertion function will also be used as the first input parameter. However, every() will return true only when all elements in the array meet the conditions of the assertion function. When one element does not meet the conditions, every() will stop traversing and return false.
let myArray = [4,1,2,3];
let count = 0; // Used to record the number of iterations
let result = myArray.every(num => {
    count++;
    num *= 3;
    return num > 5;
});
console.log(result,"The number of iterations is",count) 
// The print value is false, and the number of iterations is 2

    as long as one of the conditions is met, the some() function will stop traversal and return the value of true.

let myArray = [4,1,2,3];
let count = 0; // Used to record the number of iterations
let result = myArray.some(num => {
    count++;
    num *= 3;
    return num > 5;
});
console.log(result,"The number of iterations is",count) 
// The print value is false, and the number of iterations is 2

   it should be noted here that the results of multiplying the elements of myArray array by 3 are 1, 6 and 9, of which 6 and 9 meet the condition of greater than 5, but they return the elements in myArray, that is, 2 and 3 without operation. (elements that do not meet the conditions will not be returned. Unlike map(), the length of the array returned by map() is the same as the original array.)

Processing of sparse arrays

  sparse array definition:

A sparse array is an array whose elements do not have an index starting from 0. Normally, the length attribute of the array indicates the number of elements in the array. If the array is sparse, the value of the length attribute will be greater than the number of elements.

    for normal arrays, such as let myArray = [0,1,2], the length of this array is 3, the number of elements is 3, which is the same as the length of the array, and the indexes are 0, 1, and 2 in turn.
  simple practice of sparse array:

let testArray = new Array(10);  //The array length is 10
testArray[20] = 1	//Array length is 20
console.log(testArray) //	The print result is [< 20 empty items >, 1]

   at this time, the length of the array is 21 and there is only one element, which becomes a sparse array. The actual application scenario of creating sparse arrays may occur when using delete to delete array elements, such as:

let myArray = [1,2,3]
delete  myArray[1]
console.log(myArray,"The length of the array is",myArray.length)
console.log(1 in myArray)
//	The print result is
//	[1, < 1 empty item >, 3] the length of the array is 3
//	Is the element with index 1 false

  delete does not change the length of the array, nor does it change the index values of other elements, so it will form a sparse array. If you want the element index value to change with the deletion of array elements, you can use the splice () method.

The forEach() method does not traverse missing elements in a sparse array

let myArray = [4,,2,3];
console.log("myArray",myArray)  
// The print value is: myArray [4, < 1 empty item >, 2, 3]
let count = 0; // Used to record the number of iterations
myArray.forEach(num => {
    count++;
});
console.log("The length of the array is",myArray.length,"The number of iterations is",count) 
// The length of the array is 4 and the number of iterations is 3

map() also does not traverse the missing elements in the sparse array, but its return value array is the same length as the original array, and the location of the missing elements is the same

let myArray = [4,,2,3];
console.log("myArray",myArray)
// The print value is: myArray [4, < 1 empty item >, 2, 3]
let count = 0; // Used to record the number of iterations
let result = myArray.map(num => {
    count++;
    return num*3
});
console.log("The length of the array is",myArray.length,"The number of iterations is",count,"The returned array is",result)
// The print value is: the length of the array is 4 
// The number of iterations is 3 
// The returned array is [12, < 1 empty item >, 6, 9]

The return value of filter () does not contain missing elements in a sparse array

let myArray = [4,,2,3];
console.log("myArray",myArray)
// The print value is: myArray [4, < 1 empty item >, 2, 3]
let count = 0; // Used to record the number of iterations
let result = myArray.filter(num => {
    count++;
    return num>1
});
console.log("The length of the array is",myArray.length,"The number of iterations is",count,"The returned array is",result)
// The print value is: the length of the array is 4
// The number of iterations is 3
// The returned array is [4, 2, 3]

Keywords: Javascript Front-end ECMAScript Vue

Added by adrian_melange on Wed, 22 Dec 2021 07:55:17 +0200