微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 nodejs 中使用递归遍历每个元素?

如何解决如何在 nodejs 中使用递归遍历每个元素?

下面是我的 JSON 代码,我也是通过递归添加的,这是一个不同的代码。直到这里它给出了这个 JSON 格式树。但在那之后,我试图访问这棵树的每个元素,但在 children 数组中出现错误

const familyTree =   {
            "name": "Shan","gender": "Male","grandfather": "null","grandmother": "null","father": "null","mother": "null","wife": {
                "name": "Anga","husband": "Shan","fil": "null","mil": "null","children": [{
                    "name": "Chit","father": "Shan","mother": "Anga","wife": {}
                },{
                    "name": "Ish",{
                    "name": "Vich",{
                    "name": "aras",{
                    "name": "Satya","gender": "Female","husband": "","children": []
                }]
            }
    }

我正在尝试下面的代码,但是当它开始循环遍历妻子内部的孩子时出现错误。为什么????????????????

 display(familyTree);
var husbandName = 'Chit';
var wifeName = 'Amba';
    const display = async(person) => {
      console.log("person.name = "+ person.name);
      if(person.name == husbandName) {
        var wife = {
          name:wifeName,husband:husbandName,fil:person.father,mil:person.mother,children : []
        }
        person.wife = wife;
        console.log("wife = "+JSON.stringify(wife));
      }
      if (person.wife) {
        console.log("person.wife = "+ JSON.stringify(person.wife));
        person.wife.children.forEach(display);
      }
    }

这是控制台错误

(

node:8528) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
    at display (C:\Users\em\Desktop\MindGrep\logic\index.js:103:30)

解决方法

根据根 treeFamily 对象,您递归调用 display 对象可能有一个指向空对象的wife 属性 - 即没有定义的 children 属性。

从您的 familyTree 对象 children 中,完全删除指向空对象的 wife 属性,或者向它们添加指向空数组的 children 属性。

,

嗨,我运行了你的代码,但除了函数声明之外运行良好。

const familyTree = {
  name: "Shan",gender: "Male",grandfather: "null",grandmother: "null",father: "null",mother: "null",wife: {
    name: "Anga",husband: "Shan",fil: "null",mil: "null",children: [
      {
        name: "Chit",father: "Shan",mother: "Anga",wife: {}
      },{
        name: "Ish",{
        name: "Vich",{
        name: "Aras",{
        name: "Satya",gender: "Female",husband: "",children: []
      }
    ]
  }
};

var husbandName = "Chit";
var wifeName = "Amba";
const display = async(person) => {
  console.log("person.name = " + person.name);
  if (person.name == husbandName) {
    var wife = {
      name: wifeName,husband: husbandName,fil: person.father,mil: person.mother,children: []
    };
    person.wife = wife;
    console.log("wife = " + JSON.stringify(wife));
  }
  if (person.wife) {
    console.log("person.wife = " + JSON.stringify(person.wife));
    person.wife.children.forEach(display);
  }
};

display(familyTree);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。