我有2個類,生物類將節點數組作爲屬性。但是這些生物也將被列入陣列。我希望能夠從任何節點獲取生物索引。目前我所能做的就是能夠從生物本身獲取生物索引。我一直在嘗試着使用生物類中的集合函數來設置生物的生物索引號,並將所有節點的生物索引號設置爲相同的數字。數組的嵌套類,想抓取外層數組的索引
//Node class
class Node {
constructor(x, y, r, color, highlight, highlightColor) {
this.x = x;
this.y = y;
this.r = r || 20;
this.color = color || "#ff0";
this.highlight = highlight || false;
this.highlightColor = highlightColor || "#0000FF";
}
}
// Creature class
class Creature {
constructor(nodes, muscles, nodeColors) {
this.nodes = nodes;
this.muscles = muscles;
this.nodeColors = nodeColors || "#ff0";
Object.defineProperties(this, {
nodesArray: {
"get": (i) => this.nodes[i],
"set": nodes => {
this.nodes[i] = newNode;
}
},
musclesArray: {
"get": (i) => this.nodes[i],
"set": muscles => {
this.muscles[i] = newMuscle;
}
},
creatureNumber: {
"get":() => creatures.indexOf(this),
}
});
}
}
var nodes = [
new Node(100, 100),
new Node(200, 200)
];
var creatures = [
new Creature(nodes, muscles)
];
我讀過你的問題了幾次,我不知道你想TP達到什麼目的。你可以添加一個小例子數組,並基於這個數組解釋你需要得到什麼? – Thijs
爲了解決您的問題並且同時獲得更好的性能,也許您應該考慮將ID明確存儲在Creature對象中(因爲「array.indexOf」效率不高,O(N))。 – Joel
@Thijs數組在片段中。基本上我會有這兩個數組。每個將擴展他們各自的類。每個生物都會擁有一組節點。我想要做的就是隻能取得其中一個節點,並能夠抓住其他生物陣列中生物的索引。希望這是有道理的。 – Chenny