📅  最后修改于: 2023-12-03 15:33:01.156000             🧑  作者: Mango
In JavaScript, the indexOf()
method is used to find the index of a specific element in an array. This method returns the index of the first occurrence of the element in the array. However, when it comes to multidimensional arrays, the indexOf()
method behaves differently.
The syntax for the indexOf()
method is as follows:
array.indexOf(element, start);
array
: The array in which to search for the elementelement
: The element to search forstart
: The index at which to start the search (optional)When dealing with multidimensional arrays, the indexOf()
method becomes more complicated. It only works as expected when searching for a simple value in a one-dimensional array. For example:
const arr = ["apple", "banana", "cherry", "banana"];
const index = arr.indexOf("banana");
console.log(index); // Output: 1
However, when searching for a value in a multidimensional array, the indexOf()
method will not work as expected. It will only check the first level of the array for the value and return -1 if it cannot be found. For example:
const arr = [[1, 2], [3, 4], [5, 6]];
const index = arr.indexOf([3, 4]);
console.log(index); // Output: -1
To search for an element in a multidimensional array, we can use the findIndex()
method instead. This method works by iterating over the array and returning the index of the first element that satisfies a given condition.
To search for a specific value in a multidimensional array, we can use the JSON.stringify()
method to convert each element in the array to a string and then compare the resulting strings to the target string. For example:
const arr = [[1, 2], [3, 4], [5, 6]];
const target = [3, 4];
const index = arr.findIndex(element => JSON.stringify(element) === JSON.stringify(target));
console.log(index); // Output: 1
In this example, we use the findIndex()
method to iterate over the array and execute the callback function for each element. The callback function compares the stringified version of each element to the stringified version of the target value, and returns true
if they match.
When searching for values in multidimensional arrays in JavaScript, the indexOf()
method alone is not enough. Instead, we can use the findIndex()
method and compare stringified versions of the elements to search for specific values.