javascript - 在js中访问子对象

标签 javascript hierarchy

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 对象访问地球的半径?以下返回 Undefined alert(solarSystem.children.radius);

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

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

有人可以帮帮我吗?

最佳答案

I have the code above in JS. How can I access for example the radius of earth using the solarSystem object? The following returns Undefined alert(solarSystem.children.radius);

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

How should I call children in a recursive function as follows.

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);

关于javascript - 在js中访问子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47413046/

相关文章:

java - RTS 游戏中对象的多态性和类层次结构问题

iphone - 如何管理 UIViewController 中的 uiview 层次结构?

for-loop - AngularJS:如何在分层数据集合上使用 ng-repeat

javascript - 使用 SnapSVG 的响应式 SVG 路径

javascript - 自定义元素大小不正确

javascript - 文件系统 Nodejs : "Uncaught TypeError: fs.writeFileSync is not a function"

javascript - 在单个网页中嵌入多个视频流

javascript - Cloudflare IP 地理定位替代方案?在 JavaScript 或 PHP 中?

mysql - SQL层次结构计数

sql-server - "flatten"层次结构表的快速方法?