我正在嘗試使用“節點”類建構式創建一個物件陣列。每個節點都應該有一個包含相鄰節點的陣列。當我使用 for 回圈遍歷每個 Node 以添加鄰居時,它會觸發類方法,但 Node 物件無法更新。
這是我正在做的人為/簡化版本:
export default class Node {
neighbours: Node[];
addNeighbours: (thisNode: Node) => void;
constructor() {
this.neighbours = [];
this.addNeighbours = function (thisNode: Node) {
thisNode.neighbours = []
this.neighbours.push(thisNode)
console.log(this.neighbours.length); // returns 1. So this is being triggered and appears to be working.
}
}
}
// Create an array to represent the 2D grid.
export function createArrayOfNodes(): Node[][] {
let returnGrid: Node[][] = [
[new Node(), new Node(), new Node()],
[new Node(), new Node(), new Node()],
[new Node(), new Node(), new Node()],
]
// add neighbours to each Node
for (let i = 0; i < returnGrid.length; i ) {
for (let j = 0; j < returnGrid.length; j ) {
const newJ = j 1 === returnGrid.length ? 0 : j 1
returnGrid[i][j].addNeighbours(returnGrid[i][newJ]); // This fails to add a neighbour
// returnGrid[i][j].addNeighbours(new Node()); // This adds a neighbour OK
}
}
// returnGrid[0][0].addNeighbours(returnGrid[0][1]); // This adds a neighbour OK
return returnGrid;
}
console.log(createArrayOfNodes) // Returns an array of Nodes, but they don't have any Nodes in their neighbour properties.
根據注釋掉的代碼,neighbours
如果屬性在for
回圈之外,我可以更新它。如果我在for
回圈中,我可以在neighbours
創建新節點時更新屬性,但如果我嘗試從returnGrid
. 誰能解釋一下?
uj5u.com熱心網友回復:
似乎以下行使您的代碼不起作用。評論它一切正常。
thisNode.neighbours = [];
節點應如下所示
export default class Node {
neighbours: Node[];
addNeighbours: (thisNode: Node) => void;
constructor() {
this.neighbours = [];
this.addNeighbours = function (thisNode: Node) {
this.neighbours.push(thisNode);
};
}
}
實際上,您可以定義addNeighbours
建構式的外部。
export default class Node {
neighbours: Node[];
constructor() {
this.neighbours = [];
}
addNeighbours = function (thisNode: Node) {
this.neighbours.push(thisNode);
};
}
作業示例,
uj5u.com熱心網友回復:
每次呼叫該addNeighbours
方法時,都會重新分配neighbours
傳遞的陣列Node
。這將有效地重置neighbours
傳遞的陣列Node
。
洗掉thisNode.neighbours = []
線。
class Node {
neighbours = [];
addNeighbours(thisNode) {
this.neighbours.push(thisNode)
}
}
// Create an array to represent the 2D grid.
function createArrayOfNodes() {
let returnGrid = [
[new Node(), new Node(), new Node()],
[new Node(), new Node(), new Node()],
[new Node(), new Node(), new Node()],
]
// add neighbours to each Node
for (let i = 0; i < returnGrid.length; i ) {
for (let j = 0; j < returnGrid.length; j ) {
const newJ = j 1 === returnGrid.length ? 0 : j 1
returnGrid[i][j].addNeighbours(returnGrid[i][newJ]);
}
}
return returnGrid;
}
console.log(createArrayOfNodes());
旁注:我注意到你是如何在你的Node
類上宣告你的屬性和方法的。您可以分配每個實體應在class
范圍內繼承的屬性和方法,而不是constructor
.
可constructor
用于在實體化類時斷言邏輯和處理引數。
export default class Node {
neighbours: Node[] = [];
addNeighbours(thisNode: Node): void {
this.neighbours.push(thisNode)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/468386.html
標籤:javascript 打字稿 循环 班级
上一篇:排序函式意外行為