使用javascript

时间:2017-11-10 06:45:39

标签: javascript arrays recursion vue.js vuejs2

我正在处理的一个例子 https://codepen.io/wombsplitter/pen/KyWKod

我的数组结构如下

[{
 //obj 1
 link: [{
        //obj 2
        link: [{
              //obj 3
              }]
        }]
}]

数组可以在任何“级别”保存任意数量的元素。我希望以递归方式遍历并使用渲染函数,将它们打印到页面上,同时保留它们的结构。

div.item
  div.info
  div.link
     div.info
     div.link
        div.info
        div.link
           div.info
           div.link

任何帮助,建议将不胜感激。

4 个答案:

答案 0 :(得分:0)

你的代码中有一个erorr,请参阅下面我调用arr.map你正在调用this.test.map

    renderFunction(h, arr) {
      return h('div', { class: 'link'}, arr.map(t => {
        return h('div', t.name);
    }

答案 1 :(得分:0)

懒惰的方式,应该是正确的:

function recurse(obj){
   var html = ['<div class="info"></div>'];
   html.push('<div class="link">')
   if(!!obj.link) html.push(recurse(obj.link[0]));
   html.push('</div>')
   return html.join('')
}

document.getElementsByClassName('item')[0].innerHtml = recurse(obj[0]);

答案 2 :(得分:0)

这个怎么样:

renderFunction(h, arr) {
  return renderStructure(this.test, h)
}

// outside of your App object
function rendeStructure(test, h){
  return h('div', { class: 'link'}, test.map(t => {
    return h('div', {class: 'info'}, [t.name, renderStructure(t.links, h)]);
  }))
}

这假设您的数据中没有循环。

答案 3 :(得分:0)

如果您只想要值,可以这样做:

function getVals(mixed){
  var r = [];
  function rec(mixed){
    var a;
    if(mixed instanceof Array){
      for(var i=0,l=mixed.length; i<l; i++){
        a = mixed[i];
        if(typeof a === 'object' && a !== null){
          return rec(a);
        }
        else{
          r.push(a);
        }
      }
    }
    else if(typeof mixed === 'object' && mixed !== null){
      for(var i in mixed){
        a = mixed[i];
        if(typeof a === 'object' && a !== null){
          return rec(a);
        }
        else{
          r.push(a);
        }
      }
    }
    else{
      r.push(mixed);
    }
    return r;
  }
  return rec(mixed);
}
var obj = {
  el: '#app',
  data: {
    test: [{
      name: 'parent',
      link: [{
        name: 'child1',
        link: [{
          name: 'child2',
          deepObj: {
            deepProp:'Number 7 test',
            num:7,
            deeperArray:[true, false, 'test', 'in', 'here', 1]
          }
        }]
      }]
    },
    {
      name: 'parent2'
    }]
  }
}
var vals = getVals(obj);
// getVals returns an Array, hence the .join()
console.log(vals.join(', ')); console.log(vals);