我用JavaScript和Selenium编写测试脚本,并且想查询是否给出了可选参数(如果提供),请使用它们,否则,请跳过它们。
/*optional parameter are: day, month, year, comment*/
if( typeof day !== 'undefined') {
entryField.sendKeys(day);
}
if( typeof year!== 'undefined') {
entryField.sendKeys(year);
}
if( typeof month!== 'undefined') {
entryField.sendKeys(month);
}
if( typeof comment !== 'undefined') {
entryField.sendKeys(comment);
}
这看起来很丑。有更好的方法吗? 该参数是从外部给出的,因此,如果我不执行这种typeof-Query,则会发生引用错误,因为未定义它们。
答案 0 :(得分:1)
我认为最棘手的部分是变量day
等可能在代码的这一部分之前甚至不存在。因此,为了避免出错,一种可能的方法是使用eval
,如下所示:
var para = ["day", "year", "month", "comment"];
for(let p of para) {
if(eval("typeof "+p) !== 'undefined') {
entryField.sendKeys(eval(p));
}
}
答案 1 :(得分:0)
您可以将forEach与一系列操作结合使用,以提高可读性:
var actions = [day, year, month, comment]
actions.forEach(action => {
if (typeof action !== 'undefined') {
entryField.sendKeys(action);
}
})
答案 2 :(得分:0)
我只使用rest参数,所以我将不用fn(day, year, month, comment)
:
function fn(...keys) {
keys.filter(it => it !== undefined)
.forEach(it => entryField.sendKeys(it));
}