简体   繁体   English

在 `for`–`in` 循环中从 object 访问属性会导致 `undefined`

[英]Accessing properties from object in `for`–`in` loop results in `undefined`

I have these two classes:我有这两个类:

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

I'm simply trying to call printGraph to print all the nodeId s this way:我只是试图调用printGraph以这种方式打印所有nodeId

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

But it's printing undefined .但它正在打印undefined I can't seem to figure out why it isn't simply printing the nodeId .我似乎无法弄清楚为什么它不只是打印nodeId

I think the problem may be that you are using "for in" loop instead of "for of" to iterate over an array.我认为问题可能是您使用“for in”循环而不是“for of”来迭代数组。

"for in" loop is used to iterate object properties “for in”循环用于迭代 object 属性

you are using the wrong for loop.您使用了错误的 for 循环。 Try changing it to:尝试将其更改为:

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

A for..of loop should loop over the node the way you want. for..of 循环应该以您想要的方式遍历节点。
Result:结果:

1
2
3

It seems you're iterating over the properties of the array object by using the in keyword.您似乎正在使用in关键字迭代数组 object 的属性。 For an array, this means you're iterating over the indices (keys) , namely 0, 1, 2 in your 3-member array.对于数组,这意味着您正在迭代索引 (keys) ,即 3 成员数组中的 0, 1, 2 。 Those are strings, and don't have a nodeId property, so your output is undefined .这些是字符串,没有nodeId属性,所以你的 output 是undefined You'll see these if you run console.log(node, typeof node) inside your current loop (staying with in ).如果您在当前循环中运行console.log(node, typeof node) (留in ),您会看到这些。

If you use the of keyword in your for loop, you'll get the values of the array, namely the objects with 1, 2 and 3 as values for nodeId .如果您在 for 循环中使用of关键字,您将获得数组的,即具有 1、2 和 3 的对象作为nodeId的值。 So all you have to do is change the in to of and you'll have the output you're after.因此,您所要做的就是将in更改为of ,您将拥有您所追求的 output。

Personally, I'd use this:就个人而言,我会使用这个:

printGraph(){
    const nodeIds = this.nodes.map(node => node.nodeId);
    console.log(nodeIds);
}

you need to print console.log(node);你需要打印console.log(node); cause you are looping trough let node in this.nodes因为你正在循环let node in this.nodes

where node is an actual node from this.nodes其中nodethis.nodes中的实际节点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM