【发布时间】:2017-06-27 17:30:35
【问题描述】:
我正在使用 Selenium 和 nodejs 来遍历一个 html 表格并将一个字符串从一个数组匹配到表格单元格中的字符串。
我的数组可能是 ["Name", "Address1", "Address2", "Address3",...] 并且 tr[1] 中的值将尝试与 Arr[0], tr[2] 匹配与 Arr[1] 等。
html 表格中的每个项目都会有一行,但如果没有数据,例如 Address2,则不会出现。
在这种情况下,tr[3] 会发现它无法与 Arr[3] 匹配。我不想移动到 tr[4],而是想看看 tr[3] 是否与 Arr[4] 匹配,然后是 Arr[5] 等。表中的项目将始终与数组中的项目的顺序相同,所以我不需要任何“不匹配”的数组项。
我已经发布了整个函数以防万一,但问题似乎很简单,因为我无法让“i = i - 1”将新值携带到下一个循环迭代中。
我已经证明我进入了 Else 部分,并且 i - 1 的值与我当时所期望的一样。
var retrieveData = function retrieveData(Arr){
j = 0
driver.findElements(webdriver.By.xpath("//*[@class='table-container']")).then (function(rows){
rowCount = rows.length;
console.log("Row count = " + rowCount);
}).then (function(fn){
for (i = 1;i < rowCount + 1; i++){
(function(i){
var element = driver.findElement(webdriver.By.xpath("//div[@class='table-container']["+i+"]/div/strong/a"));
element.getText().then(function(Type){
var typefromArray = String(Arr[j].split(':')[0]);
if (Type == typefromArray){
// Do something
j = j + 1;
} else {
// Do something
i = i - 1 // My problem looks to be here, but may be in the transfer of this back up to the beginning of the loop
j = j + 1;
}
});
})(i);
};
});
};
module.exports.retrieveData = retrieveData;
【问题讨论】:
-
您在 IIFE 中有
i = i - 1。您也可以使用i--和j++。 -
您好,感谢您的快速回复!如果字符串不匹配(即 If 语句返回 False),我只想减少计数器。如何将 i = i - 1(或 i--) 保留在 Else 之外?
-
您在
(function(i){声明中隐藏了i的范围。
标签: javascript node.js for-loop