Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将web表的定位器中的所有值相加,方法只会生成前两个定位器的值_Javascript_Protractor - Fatal编程技术网

Javascript 将web表的定位器中的所有值相加,方法只会生成前两个定位器的值

Javascript 将web表的定位器中的所有值相加,方法只会生成前两个定位器的值,javascript,protractor,Javascript,Protractor,我想添加web表中定位器的所有值,但它只添加前两个值。下面是我的方法声明 exports.GetMonthsFWSeasonSTDPreMkdValues = () => { var total_value; for(var month_index = 9; month_index <= 18 ; month_index++){ const elm_xpath = utils.GetXpathForSubCategory(chosen_season_index, mo

我想添加web表中定位器的所有值,但它只添加前两个值。下面是我的方法声明

exports.GetMonthsFWSeasonSTDPreMkdValues = () => {
  var total_value;
  for(var month_index = 9; month_index <= 18 ; month_index++){
    const elm_xpath = utils.GetXpathForSubCategory(chosen_season_index, month_index);
    return browser.element(by.xpath(elm_xpath)).getText().then(function(response_total_months_index_values){
      total_value += response_total_months_index_values;
      console.log('total value' ,total_value);
    });
  }
};
根情况是在For循环中使用return,因此循环只能迭代一次

另一个隐藏的代码问题是javascript闭包问题,For循环作为Sync执行,而getText内部循环作为Async执行

如果删除关键字return,则browser.elementby.xpathelm\u xpath.getText将重复使用月份的elm\u xpath\u index=18

exports.GetMonthsFWSeasonSTDPreMkdValues = () => {
  var promises = [];

  for(var month_index = 9; month_index <= 18 ; month_index++){
    const elm_xpath = utils.GetXpathForSubCategory(chosen_season_index, month_index);
    promises.push(element(by.xpath(elm_xpath)).getText());
  }

  return Promise.all(promises).then(function(data){

    return data.reduce(function(accumulator, currentValue){
        return accumulator + currentValue * 1;
    }, 0);

  });

};
//Remind: this function return a promise.

你应该将totalValues初始化为0。我也试过了。结果还是一样。这里有太多的未知项,有人无法找到它。您能否创建一个不依赖于您的UTIL、浏览器或对象的应用程序?在尝试这样做时,你很可能会自己发现问题!