js:给定两个数组,如何判断他们的相对应下标的元素类型是一样的

题目:

  给Array对象原型上添加一个sameStructureAs方法,该方法接收一个任意类型的参数,要求返回当前数组与传入参数数组(假定是)相对应下标的元素类型是否一致。

 

 假设已经写好了Array.prototype.sameStructureAs ,会有下面的结果:

  

[1,1].sameStructureAs([2,2])
//    true

[1,[1,1]].sameStructureAs([2,[2,2]])
//    true

[1,[1]].sameStructureAs([[2],2])
//    false

[[],[]].sameStructureAs([[],[]])
//    true

看到上面的代码返回值,或许你就明白了。sameStructureAs方法的功能就如此之简单。

那么, 该怎么实现呢,如下:

Array.prototype.sameStructureAs = function (other) {
    // Return 'true' if and only if 'other' has the same
    // nesting structure as 'this'.

    // Note: You are given a function isArray(o) that returns
    // whether its argument is an array.
    
    if (! (other instanceof Array) ) return false;    //    传入的不是数组返回false
    
    //    这个函数返回一个序列号
    function count (arr) {
      //    第一次调用添加一个index属性
      if (typeof count.index === 'undefined') {
        count.index = 0
      }
      var resStr = ''    //    返回的序列号
      
      if (!arr.length) resStr += count.index    // 如果传入数组为空,序列号为当前index属性值
      
      for (var i = 0; i < arr.length; i++) {
        if (typeof arr[i] !== 'object') {
          resStr += count.index   //  如果这个元素不是数组,序列号为当前index属性值
        } else {
          count.index++    //  将index属性值+1,是为了进入下一层数组
          resStr += count(arr[i])    //   返回当前传入数组的序列号
          count.index--      //这里 -1 是回到当前层次中,继续遍历
        }
      }
      return resStr
    }
    
    return count(this) === count(other)
    
}

思路是这样的:

  因为这仅仅判断数组,并没有其他引用类型的对象,如RegExp、Date等,所以就容易多了。

  我先设定数组第一层的非数组元素的序列号为0 ,也就是说 [1,1,1] 序列号是 [0,0,0],因此返回的数组序列号为'000',同样[2,2,2]也返回'000'

  每进入一层数组前,那么元素序列号就 +1,该循环完成并返回值后,元素序列号 - 1, 回到当前层次的数组中继续遍历。

  注: 如果当前数组为空,数组序列号应该为当前数组层次,这是为了判断在所有元素师空数组时的情况。如[[],[]]返回'11'、[[[],[]]]返回'22'。

 

posted @ 2016-11-27 20:32  _记忆  阅读(3227)  评论(0编辑  收藏  举报