对象即使存在也无法访问

时间:2018-09-13 10:04:59

标签: javascript object

我有一个JavaScript对象,当尝试对其进行迭代时,它的长度为零,访问对象内部的任何键时甚至都不确定。

init();

function init() {
  if (window.goSamples) goSamples(); // init for these samples -- you don't need to call this
  var $ = go.GraphObject.make; // for conciseness in defining templates in this function

  myDiagram =
    $(go.Diagram, "myDiagramDiv", // must be the ID or reference to div
      {
        initialContentAlignment: go.Spot.Center
      });

  // define all of the gradient brushes
  var graygrad = $(go.Brush, "Linear", {
    0: "#F5F5F5",
    1: "#F1F1F1"
  });
  var bluegrad = $(go.Brush, "Linear", {
    0: "#CDDAF0",
    1: "#91ADDD"
  });
  var yellowgrad = $(go.Brush, "Linear", {
    0: "#FEC901",
    1: "#FEA200"
  });
  var lavgrad = $(go.Brush, "Linear", {
    0: "#EF9EFA",
    1: "#A570AD"
  });

  // define the Node template for non-terminal nodes
  myDiagram.nodeTemplate =
    $(go.Node, "Auto", {
        isShadowed: true
      },
      // define the node's outer shape
      $(go.Shape, "RoundedRectangle", {
          fill: graygrad,
          stroke: "#D8D8D8"
        },
        new go.Binding("fill", "color")),
      // define the node's text
      $(go.TextBlock, {
          margin: 8,
          font: "bold 11px Helvetica, bold Arial, sans-serif"
        },
        new go.Binding("text", "key")),
      $("TreeExpanderButton", {
        margin: new go.Margin(30, 5, 5, 5)
      })
    );

  // define the Link template
  myDiagram.linkTemplate =
    $(go.Link, // the whole link panel
      {
        selectable: false
      },
      $(go.Shape)); // the link shape

  // create the model for the double tree
  myDiagram.model = new go.TreeModel([
    // these node data are indented but not nested according to the depth in the tree

    {
      key: "D",
      color: lavgrad
    },
    {
      key: "Z",
      parent: "C",
      dir: "left",
      color: bluegrad
    },
    {
      key: "C",
      parent: "D",
      dir: "left",
      color: bluegrad
    },
    {
      key: "B",
      parent: "D",
      dir: "left",
      color: bluegrad
    },
    {
      key: "I",
      parent: "H",
      dir: "right",
      color: bluegrad
    },
    {
      key: "K",
      parent: "H",
      dir: "left",
      color: bluegrad
    },
    {
      key: "K",
      parent: "E",
      dir: "left",
      color: bluegrad
    },
    {
      key: "J",
      parent: "E",
      dir: "right",
      color: bluegrad
    },
    {
      key: "H",
      parent: "D",
      dir: "right",
      color: bluegrad
    },
    {
      key: "E",
      parent: "D",
      dir: "right",
      color: bluegrad
    },

  ]);

  doubleTreeLayout(myDiagram);
}

function doubleTreeLayout(diagram) {
  // Within this function override the definition of '$' from jQuery:
  var $ = go.GraphObject.make; // for conciseness in defining templates
  diagram.startTransaction("Double Tree Layout");

  // split the nodes and links into two Sets, depending on direction
  var leftParts = new go.Set(go.Part);
  var rightParts = new go.Set(go.Part);

  var LP = leftParts;
  var items = LP.ud;

  document.getElementById("objInfo").innerHTML = "<br> Items Length : " + items.length;
  document.getElementById("objInfo").innerHTML += "<br> Object Keys Length : " + Object.keys(items).length;
  document.getElementById("objInfo").innerHTML += "<br> Object Keys: " + items;


  separatePartsByLayout(diagram, leftParts, rightParts);
  // but the ROOT node will be in both collections

  // create and perform two TreeLayouts, one in each direction,
  // without moving the ROOT node, on the different subsets of nodes and links
  var layout1 =
    $(go.TreeLayout, {
      angle: 180,
      arrangement: go.TreeLayout.ArrangementFixedRoots,
      setsPortSpot: false
    });

  var layout2 =
    $(go.TreeLayout, {
      angle: 0,
      arrangement: go.TreeLayout.ArrangementFixedRoots,
      setsPortSpot: false
    });

  layout1.doLayout(leftParts);
  layout2.doLayout(rightParts);

  diagram.commitTransaction("Double Tree Layout");
}

function separatePartsByLayout(diagram, leftParts, rightParts) {
  var root = diagram.findNodeForKey("D");
  if (root === null) return;
  // the ROOT node is shared by both subtrees!
  leftParts.add(root);
  rightParts.add(root);
  // look at all of the immediate children of the ROOT node
  root.findTreeChildrenNodes().each(function(child) {
    // in what direction is this child growing?
    var dir = child.data.dir;
    var coll = (dir === "left") ? leftParts : rightParts;
    // add the whole subtree starting with this child node
    coll.addAll(child.findTreeParts());
    // and also add the link from the ROOT node to this child node
    coll.add(child.findTreeParentLink());
  });
}
/* Copyright 1998-2014 Northwoods Software Corporation. All Rights Reserved. */

body {
  font-family: sans-serif;
  font-size: 13px;
}

p {
  max-width: 700px;
}

p.box {
  border: 1px solid #BBB;
  padding: 4px 4px 6px 4px;
}

p.warning {
  background-color: #FCD5CD
}

.diagramContainer {
  border: solid 1px blue;
}

pre {
  font-size: 9pt;
}

.footer {
  text-align: right;
  font-size: 10px;
}


/* new: */

#sample {
  margin-left: 0px;
}

#menu {
  white-space: nowrap;
  overflow: hidden;
  border: 1px solid #DDD;
  padding: 4px;
  margin-right: 5px;
  background-color: #F9F9F9;
  width: 120px;
  float: left;
}

#sections {
  list-style-type: none;
  font-size: 13px;
  padding: 0px;
  margin: 0px;
  line-height: 1.3em;
}

a {
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

a li {
  color: #0645AD;
}

a li:hover,
a li:focus {
  background: #CEDFF2;
}

a li.selected {
  background: #1E90FF;
  color: white
}

.index {
  margin-top: 0px;
}

#sample p,
#navindex,
#navtop,
.footer {
  display: none;
}
<script src="https://gojs.net/latest/release/go.js"></script>
<script src="https://gojs.net/latest/assets/js/goSamples.js"></script>
<div id="sample">
  <div id="myDiagramDiv" style="background-color: white; border: solid 1px black; width: 100%; height: 300px"></div>
  <div id="objInfo"></div>
</div>

在控制台中打印时,项目看起来像这样enter image description here

我正在尝试访问商品,但是这是不可能的。

2 个答案:

答案 0 :(得分:0)

使用Object.keys(theObject’)而不是theObject.length通过键迭代对象。或将您的物品放在数组中。

Object.keys(theObject).forEach( key=> {theObject[key]})

此外,您有异步调用,因此,当您记录或访问项目时,对象尚未完全创建。

作为证明,在此代码周围设置一个超时,然后按预期工作。

setTimeout(()=>{
  document.getElementById("objInfo").innerHTML = "<br> Items Length : " + items.length;
  document.getElementById("objInfo").innerHTML += "<br> Object Keys Length : " + Object.keys(items).length;
  document.getElementById("objInfo").innerHTML += "<br> Object Keys: " + JSON.stringify(Object.keys(items));
  }, 1000);

答案 1 :(得分:0)

请检查有效对象为if (typeof(obj[propt]) === 'object'),然后使用Object.keys(obj).forEach(function(key,index) {...}之类的迭代器