示例 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];