[英]Javascript: increment counter variable inside loop
我正在使用Selenium和nodejs遍历html表,并将数组中的字符串与表单元格中的字符串匹配。
我的数组可能是[“ Name”,“ Address1”,“ Address2”,“ Address3”,...],tr [1]中的值将尝试与Arr [0]匹配,tr [2]与Arr [ 1]等
html表中的数组中的每个项目都有一行,但是如果没有数据,例如Address2,则不会出现。
在这种情况下,tr [3]将发现它与Arr [3]不匹配。 我想看看tr [3]是否与Arr [4]匹配,然后与Arr [5]匹配,而不是转到tr [4]。表中的项目将始终与数组中的项目相同,因此我不需要任何“不匹配”的数组项。
我已经发布了整个函数(如果相关),但问题似乎非常简单,因为我无法获得“ i = i-1”来将新值携带到下一个循环迭代中。
我证明我进入了“其他”部分,并且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;
您正在for
循环中使用IIFE ,并将索引传递给该IIFE 。 看起来是为了防止i
修改而设计的!
当你做
i = i - 1
在函数的末尾,它绝对无效,因为它仅影响函数内部的i
。
这是一篇有关JavaScript变量作用域的好文章 。
但是,如果您仍然想修改i
,那么一个选择就是简单地让它由匿名函数返回并分配给外部i
变量:
.then (function(fn){
for (i = 1;i < rowCount + 1; i++){
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;
}
});
return i;
})(i);
};
这就是您所问问题的解决方案。
但是我很确定您的代码中还会有其他问题,因为您使用的是同步循环,但在异步调用的函数(该函数传递给element.getText().then
)中更新了计数器。
我建议您要么研究一下如何在JavaScript中处理异步代码(您现在正在使用Promises ),要么就要解决的更大问题提出一个更一般的问题,因为还有更多的设计障碍要解决。克服。
这是您可能需要用来处理多个Promises(不是为了复制而粘贴,为简洁起见使用ES2015)的一种模式示例:
.then(function(fn) {
Promise.all(
Array(rowCount).fill(true).map((_, i) => i + 1) // => [1..rowCount]
.map(i => {
const element = driver.findElement(webdriver.By.xpath("//div[@class='table-container']["+i+"]/div/strong/a"));
return element.getText();
})
// Here we have an array of Promises that we pass to Promise.all
// so we can wait until all promises are resolved before executing
// the following .then
).then(types => types.filter(type => type === typefromArray)
.map(type => { /* doSomething */ });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.