示例 1:使用 JSON.stringify() 比较数组
// program to compare two arrays
function compareArrays(arr1, arr2) {
// compare arrays
const result = JSON.stringify(arr1) == JSON.stringify(arr2)
// if result is true
if(result) {
console.log('The arrays have the same elements.');
}
else {
console.log('The arrays have different elements.');
}
}
const array1 = [1, 3, 5, 8];
const array2 = [1, 3, 5, 8];
compareArrays(array1, array2);
输出
The arrays have the same elements.
JSON.stringify()
方法将数组转换为 JSON 字符串。
JSON.stringify([1, 3, 5, 8]); // "[1,3,5,8]"
然后,使用 ==
比较两个数组字符串。
示例 2:使用 for 循环比较数组
// program to extract value as an array from an array of objects
function compareArrays(arr1, arr2) {
// check the length
if(arr1.length != arr2.length) {
return false;
}
else {
let result = false;
// comparing each element of array
for(let i=0; i<arr1.length; i++) {
if(arr1[i] != arr2[i]) {
return false;
}
else {
result = true;
}
}
return result;
}
}
const array1 = [1, 3, 5, 8];
const array2 = [1, 3, 5, 8];
const result = compareArrays(array1, array2);
// if result is true
if(result) {
console.log('The arrays have the same elements.');
}
else {
console.log('The arrays have different elements.');
}
输出
The arrays have the same elements.
在上面的程序中,
使用 length 属性 比较数组元素的长度。如果两个数组长度不同,则返回 false
。
否则,
- 使用
for
循环遍历第一个数组的所有元素。 - 在每次迭代中,将第一个数组的元素与第二个数组的相应元素进行比较。
arr1[i] != arr2[i]
- 如果两个数组的相应数组元素不相等,则返回
false
并终止循环。 - 如果所有元素都相等,则返回
true
。
注意:当数组元素包含对象时,上述程序将不起作用。
例如,
array1 = [1, {a : 2}, 3, 5];
另请阅读