[英]Javascript indexing array issue
嗨,我有一個包含以下數字的數組,但是當我循環遍歷eachNode函數(迭代13次)時,它將所有列表元素重復13次。 我測試了所有內容,但仍然產生錯誤,我是否正確執行了for循環?
list[61,67,78]
var len = list.length;
fd.graph.eachNode(function (node) { // loops thru all node id's in graph (13)
for (var i = 0; i < len; ++i) {
if (i in list) {
var nody = list[i]; // I put the number in a variable
var nodess = fd.graph.getNode(nody); //this takes the number and matches it with a node id, it "odjectify" it
if (node.id != nodess.id) { // if the list nodes are not the same
node.setData('alpha', 0); //
node.eachAdjacency(function (adj) { // this make the unmatched nodes disappear
adj.setData('alpha', 0, 'end');
});
}
}
}
});
不需要此行:
if (i in list)
如果in
關鍵字的右操作數包含其左操作數指定的屬性,則返回true。 與數組一起使用時,它返回意外結果。 在此情況下,此關鍵字的行為無關緊要,因此您只需將其刪除即可。
此外,您需要像這樣創建list
數組:
var list = [61, 67, 78];
...但是,當我循環遍歷
eachNode
(迭代13次)時,它將所有列表元素重復13次
事實並非如此,它實際上在eachNode
迭代了13次。 您還創建了一個for循環,該循環將按其長度遍歷list
數組。
現在,您已向我詳細說明了所需的內容,這是更新的代碼。 我希望這個對你有用:
fd.graph.eachNode(function (node) {
var flag = false;
for (var i = 0; i < len; ++i)
{
var nody = list[i];
var nodess = fd.graph.getNode(nody);
if (node.id == nodess.id) {
flag = true; break;
}
}
if (flag)
{
node.setData('alpha', 0);
node.eachAdjacency(function (adj) {
adj.setData('alpha', 0, 'end');
});
}
});
這是設計使然的行為:
您遍歷圖形(如您所說的13次),然后在每次迭代內遍歷數組(3項)。
如果只想在數組上循環一次,只需將其移出外部循環即可
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.