Home > Web Front-end > JS Tutorial > body text

javascript detects whether two arrays are similar_javascript skills

WBOY
Release: 2016-05-16 15:58:16
Original
1063 people have browsed it

JS needs to compare whether two arrays have the same elements, that is, all elements of the two arrays are the same, but the order of the elements is not necessarily the same. All you need to do is sort the arrays first, and then compare the two arrays to see if they are equal.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  <title>js 检测两个数组是否相似</title>
</head>
<body>
  <script>
    //数组中的成员类型相同,顺序可以不同。例如[1, true] 与 [false, 2]是相似的。
     //数组的长度一致。
    //类型的判断范围,需要区分:String, Boolean, Number, undefined, null, 函数,日期, window.
    function arraysSimilar(arr1, arr2){
      //判断边界
      if (!(arr1 instanceof Array) || !(arr2 instanceof Array)) {
        return false;
      }

      //判断长度
      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 typeOf(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>
</body>
</html>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!