在"for"-"in"循环中从对象访问属性会导致"undefined" [英] Accessing properties from object in `for`–`in` loop results in `undefined`

查看:86
本文介绍了在"for"-"in"循环中从对象访问属性会导致"undefined"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这两节课:

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 来打印所有 nodeId :

I’m simply trying to call printGraph to print all the nodeIds this way:

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 .

But it’s printing undefined. I can’t seem to figure out why it isn’t simply printing the nodeId.

推荐答案

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

you are using the wrong for loop. Try changing it to:

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

for..of循环应按所需方式在节点上循环.
结果:

A for..of loop should loop over the node the way you want.
Result:

1
2
3

这篇关于在"for"-"in"循环中从对象访问属性会导致"undefined"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆