题解 | #dom节点转成json数据#

dom节点转成json数据

https://www.nowcoder.com/practice/0340a0c6d11d4aadba0aef86e6ae723f

没通过测试,在本地测试为true,牛客网测试为null,我认真地看了一遍牛客网的测试代码,奇葩,离谱,不知道哪个牛马写的,如下:

需要返回json对象

但是呢,以下是测试代码,可以看到传入给isSame函数的数据是dom2json函数返回的数据(String类型),以及一个测试对象(Object类型),但是在isSame函数里,红圈部分,表达的意思却是,如果类型不一致return,由此可见,这个测试代码是错误的,

上述,只是错误之一,还有,题目要求元素的标签名,大小写皆可,但是呢,在测试代码的第29行

if (type1 === '[object String]') {

console.log(o1 === o2);

console.log(o1);

console.log(o2);

return o1 === o2;

}

可以看到在比较字符串,字符串的比较可是一定会区别大小写的呀,目前只发现了这两个错误,最下面是本人的代码:

let cal = function () {
      var el = document.getElementById('jsContainer');
      (el || {}).innerHTML = '<em class="a1" data-class="a2"></em>';
      var data = dom2json();
      var result = isSame(data, {
        tag: 'div',
        attributes: { id: 'jsContainer' },
        children: [{
          tag: 'em', attributes: { class: 'a1', 'data-class': 'a2' },
          children: []
        }]
      });
      console.log(result);
      return result;
      function isSame(o1, o2) {
        var type1 = ({}).toString.call(o1);
        var type2 = ({}).toString.call(o2);

        if (type1 !== type2) return;

        if (type1 === '[object Array]') {
          console.log(o1.join('T_T') === o2.join('T_T'));
          return o1.join('T_T') === o2.join('T_T');
        }
        if (type1 === '[object String]') {
          console.log(o1 === o2);
          console.log(o1);
          console.log(o2);
          return o1 === o2;
        }
        var key1 = Object.keys(o1).sort((a, b) => a > b ? 1 : a === b ? 0 : -1);
        var key2 = Object.keys(o2).sort((a, b) => a > b ? 1 : a === b ? 0 : -1);

        if (key1.length !== key2.length) {
          console.log(false);
          return false
        };

        return key1.every(key => isSame(o1[key], o2[key]));
      }
    }
function dom2json(node = jsContainer) {
      // 先生成对象,再转JSON
      // 遍历jsContainer.childNodes
      let domObj = {}
      if (node.nodeType == 1) {
        // 标签名
        domObj.tag = node.tagName.toLowerCase()

        // 特性
        let attri = {}
        for (let prop of node.attributes) {
          attri[prop.name] = prop.value
        }
        domObj.attributes = attri

        // 子节点
        domObj.children = []
        if (node.childNodes.length != 0) {
          for (let n of node.childNodes) {
            if (dom2json(n)) {
              domObj.children.push(dom2json(n))
            }
          }
        }
      } else if (node.nodeType == 3) {
        if (node.data.trim() == '') {
          return
        }

        domObj.tag = 'text'
        domObj.content = node.data.trim()
      }
      if (node.id == 'jsContainer') {
        return JSON.stringify(domObj)
      }
      return domObj
    }

全部评论

相关推荐

买蜜雪也用卷:我觉得应该没有哪个人敢说自己熟练使用git,代码分支一复杂还是得慢慢寻思一下的,不过基本的拉代码提交代码还有分支什么的是应该会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务