You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中生成多层嵌套对象?实现太阳系层级访问结构

Solution for Multi-Level Nested Solar System Object

Got it, let's fix that nested object structure so you can access properties like universe.system1.planet4.x easily. The issue with your current code is that you're directly adding planet properties to the top-level universe object, skipping the system layer entirely. We need to build each level step by step: first create the system objects, then populate each system with planets, each of which holds your target properties.

Here's a working implementation that builds the full universe > system > planet > [properties] hierarchy:

setInterval(onTimerTick, 1000);
function onTimerTick() {
  const systemCount = 2; // Adjust number of systems as needed
  const planetsPerSystem = 4; // Number of planets per system

  // Reset universe each tick (remove this line if you want to persist data across ticks)
  universe = {};

  // First loop: create each system in the universe
  for (let sysNum = 1; sysNum <= systemCount; sysNum++) {
    const systemKey = `system${sysNum}`;
    // Initialize the system as an empty object (critical for nesting!)
    universe[systemKey] = {};

    // Second loop: populate the current system with planets
    for (let planetNum = 1; planetNum <= planetsPerSystem; planetNum++) {
      const planetKey = `planet${planetNum}`;
      // Add a planet object with your desired properties
      universe[systemKey][planetKey] = {
        x: Math.floor(Math.random() * 100), // Example dynamic value
        y: Math.floor(Math.random() * 100),
        z: Math.floor(Math.random() * 100),
        placeholderData: [systemCount, planetsPerSystem, sysNum, planetNum]
      };
    }

    console.log(`Created ${systemKey} with ${planetsPerSystem} planets`);
  }

  // Test the multi-level access you wanted
  console.log("Direct property access example:", universe.system1.planet4.x);
  console.log("Full universe structure:", universe);
}

// Initialize the top-level universe object
let universe = {};

Key Fixes & Explanations:

  • Layered Construction: We first create each system as an empty object inside universe before adding planets to it. This is essential—you can't add properties to a non-existent object!
  • Nested Loops: The outer loop handles systems, the inner loop handles planets within each system. This builds the exact hierarchy you need.
  • Accessible Properties: Each planet is an object with explicit properties (like x, y, z) so you can access them directly with dot notation (universe.system1.planet4.x).
  • Optional Persistence: If you don't want to reset the universe every tick, remove the universe = {}; line—just make sure to use unique keys if you're adding new systems/planets over time (e.g., append a timestamp to avoid overwriting).

Your original code only added planets directly to universe, which is why you couldn't get the multi-level nesting. By explicitly creating each intermediate layer as an object, you unlock the nested access pattern you're aiming for.

内容的提问来源于stack exchange,提问作者Joshua Rosser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:07:25