Google 脚本 - 合并运算符语法在 IF 语句中不起作用
Google Script - Consolidated operator syntax not working in IF statement
Conext
我希望下面的 onEdit(e) 函数能够根据单元格的新旧值在电子表格中添加或删除行。这需要我的 IF 语句中的 OR (||) 运算符来检查值。下面是我的第一次尝试,它成功了但导致了一些奇怪的行为,例如在一次编辑后行出现然后消失(第二个 IF 语句),每当我按下 "delete" 键时出现两行,等等:
function onEdit(e) {
var range = e.range;
var newValue = e.value;
var oldValue = e.oldValue;
var targetRow = range.getRow();
//insert 2 rows if edited cell value = "a" or "b"
if (newValue === "a" || "b") {
sheet.insertRowsAfter(targetRow, 2);
}
//delete 2 rows if former cell value was "a" or "b"
if (oldValue === "a" || "b") {
sheet.deleteRows(targetRow + 1, 2);
}
}
当前使用的应用程序
- Google 张
- Google Apps 脚本
到目前为止我已经尝试过什么
当我更改 IF 语句以在每个 OR 运算符后重述变量时,干净地生成了所需的结果:
if (newValue === "a" || newValue === "b") {
sheet.insertRowsAfter(targetRow, 2);
}
if (oldValue === "a" || oldValue === "b") {
sheet.deleteRows(targetRow + 1, 2);
}
问题
是否有一种统一的形式来编写这些将继续产生预期结果的语句?随着我继续编写此函数,这些 IF 语句可能会变得更加复杂,并且需要使用 OR 和 AND 运算符检查相同的变量。为每个运算符只声明一次变量名会容易得多。
回顾一下:
我希望能够编写出如第一个代码片段所示的统一格式的代码:
if (newValue === "a" || "b") { //etc...
然而,它只有在用较长的版本编写时才能正常工作:
if (newValue === "a" || newValue == "b") { //etc...
谢谢!
您可以使用 switch 语句来合并。
switch (newValue) {
case "a":
case "b":
sheet.insertRowsAfter(targetRow, 2);
break;
default:
}
如果需要,您可以在 "OR" 整体条件中添加更多案例。
Conext
我希望下面的 onEdit(e) 函数能够根据单元格的新旧值在电子表格中添加或删除行。这需要我的 IF 语句中的 OR (||) 运算符来检查值。下面是我的第一次尝试,它成功了但导致了一些奇怪的行为,例如在一次编辑后行出现然后消失(第二个 IF 语句),每当我按下 "delete" 键时出现两行,等等:
function onEdit(e) {
var range = e.range;
var newValue = e.value;
var oldValue = e.oldValue;
var targetRow = range.getRow();
//insert 2 rows if edited cell value = "a" or "b"
if (newValue === "a" || "b") {
sheet.insertRowsAfter(targetRow, 2);
}
//delete 2 rows if former cell value was "a" or "b"
if (oldValue === "a" || "b") {
sheet.deleteRows(targetRow + 1, 2);
}
}
当前使用的应用程序
- Google 张
- Google Apps 脚本
到目前为止我已经尝试过什么
当我更改 IF 语句以在每个 OR 运算符后重述变量时,干净地生成了所需的结果:
if (newValue === "a" || newValue === "b") {
sheet.insertRowsAfter(targetRow, 2);
}
if (oldValue === "a" || oldValue === "b") {
sheet.deleteRows(targetRow + 1, 2);
}
问题
是否有一种统一的形式来编写这些将继续产生预期结果的语句?随着我继续编写此函数,这些 IF 语句可能会变得更加复杂,并且需要使用 OR 和 AND 运算符检查相同的变量。为每个运算符只声明一次变量名会容易得多。
回顾一下:
我希望能够编写出如第一个代码片段所示的统一格式的代码:
if (newValue === "a" || "b") { //etc...
然而,它只有在用较长的版本编写时才能正常工作:
if (newValue === "a" || newValue == "b") { //etc...
谢谢!
您可以使用 switch 语句来合并。
switch (newValue) {
case "a":
case "b":
sheet.insertRowsAfter(targetRow, 2);
break;
default:
}
如果需要,您可以在 "OR" 整体条件中添加更多案例。