【问题标题】:Accessing properties from object in `for`–`in` loop results in `undefined`在 `for`–`in` 循环中从对象访问属性会导致 `undefined`
【发布时间】:2021-03-15 11:26:50
【问题描述】:

我有这两个类:

class Node {
    constructor(nodeId){
        this.nodeId = nodeId;
        this.adjacencies = [];
    }

    connectToNode(nodeToConnectTo){
        this.adjacencies.push(nodeToConnectTo);
    }
}

class Graph{
    constructor(nodes){
        this.nodes = nodes;
    }

    printGraph(){
        for (let node in this.nodes){
            console.log(node.nodeId);
        }
        
    }
}

我只是想通过这种方式调用printGraph 来打印所有nodeIds:

let node1 = new Node('1');
let node2 = new Node('2');
let node3 = new Node('3');
const arr = [node1, node2, node3];
let graph = new Graph(arr);

graph.printGraph();

但它正在打印undefined。我似乎无法弄清楚为什么它不只是打印nodeId

【问题讨论】:

标签: javascript javascript-objects for-in-loop


【解决方案1】:

您使用了错误的 for 循环。 尝试将其更改为:

printGraph(){
  for (let node of this.nodes){
    console.log(node.nodeId);
  }   
} 

for..of 循环应该以您想要的方式循环遍历节点。
结果:

1
2
3

【讨论】:

    【解决方案2】:

    我认为问题可能在于您使用“for in”循环而不是“for of”来迭代数组。

    “for in”循环用于迭代对象属性

    【讨论】:

      【解决方案3】:

      您似乎正在使用 in 关键字迭代数组对象的属性。对于数组,这意味着您正在迭代 索引(键),即 3 成员数组中的 0、1、2。这些是字符串,没有nodeId 属性,所以你的输出是undefined。如果您在当前循环中运行console.log(node, typeof node),您将看到这些(与in 保持一致)。

      如果您在 for 循环中使用 of 关键字,您将获得数组的 ,即具有 1、2 和 3 的对象作为 nodeId 的值。因此,您只需将 in 更改为 of 即可获得所需的输出。

      就个人而言,我会使用这个:

      printGraph(){
          const nodeIds = this.nodes.map(node => node.nodeId);
          console.log(nodeIds);
      }
      
      【解决方案4】:

      您需要打印console.log(node); 因为你正在循环通过let node in this.nodes

      其中node 是来自this.nodes 的实际节点

      【讨论】:

      • "其中node 是来自this.nodes 的实际节点" 不,不是。 node 在这种情况下是数组中元素的键/索引。
      猜你喜欢
      • 2013-10-29
      • 2012-02-29
      • 2018-11-02
      • 2015-10-07
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多