Javascript checks whether two arrays are similar _ javascript tips-js tutorial

Source: Internet
Author: User
Javascript cannot directly use or determine whether two arrays are equal, whether they are equal or full. To determine whether the two arrays in JS are the same, you must first convert the arrays into strings and then compare them. JS needs to compare whether two arrays have the same elements, that is, all elements in the two arrays are the same, but the order of elements is not necessarily the same. You only need to sort the array first, and then compare whether the two arrays are equal.

  
   Js checks whether two arrays are similarScript // The member types in the array are the same, and the order can be different. For example, [1, true] is similar to [false, 2. // The length of the array is the same. // Type judgment range, which must be distinguished: String, Boolean, Number, undefined, null, function, date, window. function arraysSimilar (arr1, arr2) {// judge the boundary if (! (Arr1 instanceof Array) |! (Arr2 instanceof Array) {return false;} // judge the length if (arr1.length! = Arr2.length) return false; var I = 0, n = arr1.length, countMap1 = {}, countMap2 = {}, t1, t2, TYPES = ['string', 'boolean ', 'number', 'undefined', null, 'function', 'date', 'window']; for (; I <n; I ++) {t1 = typeOf (arr1 [I]); t2 = typeOf (arr2 [I]); if (countMap1 [t1]) {countMap1 [t1] ++ ;} else {countMap1 [t1] = 1;} if (countMap2 [t2]) {countMap2 [t2] ++;} else {countMap2 [t2] = 1;} function typ EOf (ele) {var r; if (ele = null) r = 'null'; else if (ele instanceof Array) r = 'array '; else if (ele = window) r = 'window'; else if (ele instanceof Date) r = 'date'; else r = typeof ele; return r ;} for (I = 0; I <TYPES. length; I ++) {if (countMap1 [TYPES [I]! = CountMap2 [TYPES [I]) return false;} return true;} document. write (arraysSimilar ([1, true], [false, 2]); script

The above is all the content of this article. I hope you will like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.