[英]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.