有人可以从 Browserstack 解释这个 JavaScript for 循环吗?

Can some please explain this JavaScript for loop from Browserstack?

我正在使用 BrowserStack 运行 我的测试自动化 - 在他们的网站上有一个配置示例来设置 'commonCapabilities'。

我知道这是基本的 JS,但是这个 for 循环中的双管道有什么用?

// Code to support common capabilities
exports.config.multiCapabilities.forEach(function(caps){
  for(var i in exports.config.commonCapabilities) caps[i] = caps[i] || exports.config.commonCapabilities[i];
});

完整配置:

https://www.browserstack.com/automate/protractor

exports.config = {
  'seleniumAddress': 'http://hub-cloud.browserstack.com/wd/hub',

  'commonCapabilities': {
    'browserstack.user': 'xxxx',
    'browserstack.key': 'xxxx'
  },

  'multiCapabilities': [{
    'browserName': 'Chrome'
  },{
    'browserName': 'Safari'
  },{
    'browserName': 'Firefox'
  },{
    'browserName': 'IE'
  }]
};

// Code to support common capabilities
exports.config.multiCapabilities.forEach(function(caps){
  for(var i in exports.config.commonCapabilities) caps[i] = caps[i] || exports.config.commonCapabilities[i];
});

这是一个更容易读懂的表达方式:

for(var i in exports.config.commonCapabilities) {
  caps[i] = (caps[i] || exports.config.commonCapabilities[i]);
}

表示return caps[i]如果可以转为true;否则,return exports.config.commonCapabilities[i]。如果 caps[i] 未定义,因为这是一个错误的值,它会将变量设置为 exports.config.commonCapabilities[i]。这是确保每一个都被定义的方法,否则回退到一些标准配置。

这部分:caps[i] = caps[i] || exports.config.commonCapabilities[i] 基本上是说如果 caps[i] 未定义(或 null、false、0、NaN、“”(不是虚假值))运行 比 caps[i] = exports.config.commonCapabilities[i].

例如:

var x = x || "value"

具有相同的功能
if(x){/*nothing as it is already assigned*/} else {x = "value"}

If the first value is false, it checks the second value. If it's true, it returns true and if it's false, it returns false. If the first value is true, it always returns true, no matter what the second value is. from here