需要帮助来解决变量范围问题

时间:2017-02-27 03:27:47

标签: javascript node.js selenium

我无法访问names内的driver.executeScript数组。请提出解决方案;

var webdriver = require('selenium-webdriver'),
  By = webdriver.By,
  until = webdriver.until;
var driver = new webdriver.Builder().forBrowser('chrome').build();

var flow = webdriver.promise.controlFlow();
var names = ["name1", "name2"];
var len = names.length;
var j = 0
for (var i = 0; i < len; i++) {
  flow.execute(function() {
    console.log(names[j]); //this works fine.
    driver.executeScript(function() {
      //console.log(names[j]);  //this gives errror [WebDriverError: unknown error: names is not defined]
      //console.log('testing'); //this never logs
    });
    j++;
  });
}

2 个答案:

答案 0 :(得分:2)

您可以使用参数定义函数,并将名称传递给它;

for(var i=0;i<len;i++){
    flow.execute(function(){
        console.log(names[j]); //this works fine.
        driver.executeScript(func(names[j]))
        j++;
    });
}

function func(name) {
    console.log(name);
    console.log('testing');
}

最好避开访问全局变量,尝试传递变量&amp;让他们保持可读性和安全性。可维护的代码。

答案 1 :(得分:1)

注意:谢谢@bureaquete的回答。这对我也有用。

var webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until;
var driver = new webdriver.Builder().forBrowser('chrome').build();

var flow = webdriver.promise.controlFlow();
var names = ["name1","name2"];
var len = names.length;
var j=0
for(var i=0;i<len;i++){
    flow.execute(function(name) {
    return function(){
        var str = console.log(name);
    }
    }(names[j]));
j++ 
}