
在JavaScript中,数组是一个带有索引作为键和数组值作为数组对象特定键的值的对象。有时,我们需要检查两个数组是否相同。
我脑海中首先想到的解决方案是使用等号操作符,像array1 == array2这样进行比较。哎呀!这样是行不通的,因为数组是一个对象,在JavaScript中我们不能直接比较两个对象。所以,我们必须比较数组的每个元素。
在本教程中,我们将学习使用不同的方法来比较两个JavaScript数组对象。
Use the sort() method of JavaScript and compare every element
sort()方法允许我们在JavaScript中对数组值进行排序。之后,我们可以使用for循环来比较数组中每个索引处的元素。如果任何索引处的元素不匹配,我们可以说这两个数组对象是不同的。
立即学习“Java免费学习笔记(深入)”;
Syntax
用户可以按照以下语法使用sort()方法和for循环来比较两个数组对象。
// sort arrays first
arra1.sort();
array2.sort();
if (array1.length != array2.length) {
// arrays are not the same
} else {
for () {
// if elements at index i are not the same, return false
}
}
}
// both arrays are the same
Algorithm
用户可以按照以下算法进行操作。
Step 1 − Use the sort() method to sort both arrays.
步骤2 - 比较两个数组的长度;如果长度不相同,则返回false,表示两个数组不相同。
步骤 3 − 如果两个数组的长度相同,则使用for循环遍历两个数组。
Step 4 − Compare the elements of both arrays at every index, and if the elements at the index don’t match, return false.
步骤 5 - 如果两个数组中的所有元素都匹配,则两个数组相同。
Example
在下面的示例中,我们创建了两个数字数组,并使用sort()方法对它们进行排序。然后,我们使用for循环来比较两个数组的每个元素。
In the output, users can see that both arrays are the same as both arrays contain the same values.
Using the array.sort() method and for loop to check if two arrays are the same using JavaScript
使用forEach循环和indexOf()方法
We can use the forEach loop to iterate through every array element. The indexOf() method finds the first occurrence of the element in the array and returns -1 if the reference array doesn’t contain the element.
Syntax
用户可以按照以下语法使用forEach循环和indexOf()方法来比较两个数组对象。
if (array2.length != array1.length) {
// array are not the same
return false;
} else {
array1.forEach((element) => {
if (array2.indexOf(element) == -1) {
return false;
}
})
}
Algorithm
In this algorithm, we don’t need to sort the arrays like the first approach.
步骤 1 - 检查两个数组的长度是否相同;如果不相同,则返回 false。
Step 2 − If the lengths are the same, use the forEach() loop to iterate through every element.
步骤 3 − 对于数组1的每个元素,使用indexOf()方法检查其是否存在于数组2中。
第四步 - 如果indexOf()方法对于任何一个元素返回-1,则意味着两个数组不相同。
Example
In the example below, when the user clicks the button, it will invoke a compareArray() function. The compareArray() function compares the two arrays of string elements.
在输出中,用户可以观察到两个数组不相同,因为两个数组的值是不同的。
Using the forEach() loop and indexOf() method to check if two arrays are the same using JavaScript
我们已经学习了两种不同的方法来比较JavaScript中的两个数组。用户可以使用第一种方法来比较包含重复值的数组,而第二种方法只适用于比较包含唯一值的数组。
Also, users can use the JSON.stringify() method to compare the array of objects and sorted arrays.











