【问题标题】:Access child Object in js在js中访问子对象
【发布时间】:2023-04-11 12:44:01
【问题描述】:
function Luminary(radius, orbitRadius, speed, children) {
    this.radius = radius;
    this.orbitRadius = orbitRadius;
    this.speed = speed;
    this.children = children;
}

function initSolarSystem() {
    var moon = new Luminary(0.02, 0.2, 0.0015, []);
    var earth = new Luminary(0.1, 0.7, 0.001, [moon]);
    var sun = new Luminary(0.3, 0.0, 0.0, [earth]);
    return sun;
}

var solarSystem = initSolarSystem();
  1. 我在 JS 中有上面的代码。如何使用 solarSystem 对象访问例如地球的半径?以下返回未定义 alert(solarSystem.children.radius);

  2. 我应该如何在递归函数中调用孩子,如下所示:

    function draw(obj) {
        // draw Current Object 
        if (obj.children != undefined) {
          draw(obj.children);
        }
    }
    
    draw(solarSystem);
    

有人可以帮帮我吗?

【问题讨论】:

  • solarySystem.children[0].radius

标签: javascript hierarchy


【解决方案1】:

首先你的.children 是一个数组。所以打电话给.children[i].radius
第二:

if (obj.children != undefined) {
  draw(obj.children);
}

您在这里调用一次完整的children 数组的绘制函数。所以你需要实现一个for循环。

为此有很多选择,这是我的方法:

function Luminary(name, radius, orbitRadius, speed, children = []) {
    this.name = name;
    this.radius = radius;
    this.orbitRadius = orbitRadius;
    this.speed = speed;
    this.children = children;
}

function initSolarSystem() {
    var moon = new Luminary("moon", 0.02, 0.2, 0.0015);
    var earth = new Luminary("earth", 0.1, 0.7, 0.001, [moon]);
    var sun = new Luminary("sun", 0.3, 0.0, 0.0, [earth]);
    return sun;
}

var solarSystem = initSolarSystem();

function draw(obj) {
    // Draw current object.
    for (let key in obj.children)
      if (obj.children.hasOwnProperty(key)) {
        //if (typeof(obj.children) == "array") {
      	  console.log(obj.children[key].radius);
          draw(obj.children[key]);
        }
}

draw(solarSystem);

【讨论】:

    【解决方案2】:

    我在 JS 中有上面的代码。我如何访问例如半径 地球使用 solarSystem 对象?以下返回未定义 警报(solarSystem.children.radius);

    solarSystem.children是一个数组,所以使用solarSystem.children[0].radius

    我应该如何在递归函数中调用孩子,如下所示。

    function draw(obj) 
    {
      // draw Current Object
    
      if (obj.children != undefined) 
      {
        obj.children.forEach( s => draw(s) ); //invoke draw in a loop
        //draw(obj.children[0]); //use 
      }
    }
    
    draw(solarSystem);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多