【问题标题】:How to create child object inside array on each click in javascript如何在javascript中的每次点击时在数组内创建子对象
【发布时间】:2019-06-16 03:42:38
【问题描述】:

我想在每次单击按钮时插入对象作为现有最后一个对象的子对象。

这是我的代码:

const Myarray = [
    { id: 1, child:[] }
]

handleArrayDepth = (Myarray) => {

    Myarray.map(arrayitem => {
      let id = arrayitem.id;
      id++;
      arrayitem.child.push({
        id: id,
        child: []
      });
      if (id < 2) {
        this.handleArrayDepth(arrayitem.child);
      }
    });
};
console.log(Myarray);

这是我的初始数组的日志。

0:{
  id: 1,
  child: []
}

如果我点击按钮 2 次,我会得到如下输出:

0:{
  id: 1,
  child: [
    0:{
      id: 2,
      child: []
    },
    1:{
      id: 3,
      child: []
    }
  ]
}

但我想要如下所示:

0:{
  id: 1,
  child: [
    0:{
      id: 2,
      child: [
        0:{
          id: 3,
          child: []
        }
      ]
    }
  ]
}

每次点击都应该递归/无限地进行。我找不到有效的方法来做到这一点。

【问题讨论】:

  • 你到底为什么要重新定义Array?您将如何创建new Array 或检查Array.isArray
  • array 应该是arrayitem
  • 我刚刚发布了我的代码插图。这不是一个确切的代码。

标签: javascript arrays object ecmascript-6


【解决方案1】:

一些问题

  • 不要使用Array作为变量名
  • 当您不从它返回值或改变值时,不要使用 map
  • array.id 没有意义,因为您的原始代码中没有任何名为 array 的变量

你可以稍微修改你的代码,如果子长度大于0则进行递归调用,否则推送值

const array = [{id: 1,child: []}]

handleArrayDepth = (arr) => {
  arr.forEach(({id,child}) => {
    id++;
    if (child.length) {
      handleArrayDepth(child);
    } else {
      child.push({id: id, child: [] });
    }
  });
};
handleArrayDepth(array)
handleArrayDepth(array)
console.log(array);

【讨论】:

    【解决方案2】:

    只使用一个引用最后插入的对象的持久变量可能更容易:

    const array = [{
      id: 1,
      child: []
    }];
    let lastParent = array[0];
    
    const handleArrayDepth = () => {
      const { id, child } = lastParent;
      lastParent = { id: id + 1, child: [] };
      child.push(lastParent);
    };
    
    handleArrayDepth();
    handleArrayDepth();
    console.log(array);

    【讨论】:

    • 您好,非常感谢您的回答!但是const array 本身可以有更多的对象。因此,在这种情况下,使用array[0] 可能需要另一个循环来处理array
    【解决方案3】:

    改用闭包函数怎么样

    const data = [];
    
    const handleArrayDepth = (function() {
        let id = 1;
        return function(arr) {
            if (!arr.length) {
                arr.push({ id: id, child: [] });
            } else {
                id = arr[0].id + 1;
                handleArrayDepth(arr[0].child);
            }
        }
    })();
    
    function handleClick() {
     const ul = document.getElementById("list");
     let item = document.createElement("li");
     handleArrayDepth(data);
     item.innerHTML = JSON.stringify(data);
     ul.appendChild(item);
    }
    
    document.getElementById("handler").addEventListener("click", handleClick);
    ul {
     list-style-type: none;
     margin: 0;
     padding: 0;
    }
    
    ul li {
     padding: 10px 10px;
     border: 1px solid #ccc;
     margin: 5px 0;
     border-radius: 4px;
    }
    <button id = "handler">Click Me!</button>
    <ul id = "list">
    
    </ul>

    【讨论】:

      猜你喜欢
      • 2014-03-09
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 2019-06-20
      • 2019-12-23
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多