The two Object arrays are equivalent to equal method instances in JS.

1. Problem

In JS, it is not possible to calculate whether the two arrays are equal to whether or not they are equal, then the array is required. Comparison;

There are several ways to compare two arrays, why is it a secondary solution? Because it is not true to compare two arrays.

1. Transform the two arrays to the form of a string, as follows:

a. When the two array elements type is the same, the order is the same, the direct judgment is equal, the result is not equal After the conversion is a string, the results are equal;

VAR A = [1, 2, 3, 4]; var b = a.slice (); console.log (a); console.log (b); console.log (a == b); console.log (json.stringify (a) == JSON.STRINGY (B));
   

2. When the two array element types are different, the order is the same, to transform to TOSTRING () String, equal; transform with stringify into strings, the result is not equal;

JS中比较两个Object数组是否相等方法实例

VAR A = [1, 2, 3, 4]; var b = [‘ 1 ‘, 2, 3, 4]; console.log (a); console.log (b); console.log (a.tostring () == b.toString ()); console.log (json.stringify a) == JSON.STRINGYFY (B));
   
3. When the two arrays are not the same, first sort, and then convert to the JSON string comparison The result is equal:

VAR A = [1, 2, 3, 4]; var b = [4, 2, 3, 1]; console.log (a . Sort ()); console.log (b.sort ()); console.log (json.stringify (a.sort ()) == json.stringify (b.sort ())); JS中比较两个Object数组是否相等方法实例

Operation results:
   
When the array contains Object, first sort, then compare, result Equal:

VAR A = [{“X”: “ABC”}, 2, 3, 4]; var b = [4, 2, 3, {” X “:” ABC “}]; console.log (a.sort ()); console.log (b.sort ()); console.log (json.stringify (a.sort ()) == json.stringify (B.Sort ()));

Operation results: JS中比较两个Object数组是否相等方法实例

from above It can be seen:
 1. If the two array element types are the same, the order is the same, and the string is converted into a string after the string;   2. If the two array element types are the same, When the order is not the same, after sorting, use StringIfy to convert to a string and then compare; 
3. Two array elementsThe type does not translate it with stringify to the string to compare, the array is not equal; converted to a string with toString () to compare, the array is equal;

The above is all related knowledge points introduced. The content needs to be supplemented, and the later small series will improve the relevant content, and you can learn from the related articles below.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment