首页 > 解决方案 > 如何让 Google Scripts 比较 IF 语句中 .getvalues 中的 2 个变量?

问题描述

我现在正在为一个小项目使用一些谷歌脚本,以前我使用过 VBA,但无论如何我都不是编码专家。

情况是这个 Values2 和 Rowd2 完全相同,我已经通过在它们的任何一个位置输入确切的值来测试 if。

例如,在调试时它们都是“名字”,当我与“名字”进行比较时,它们都会在 IF 上触发 TRUE,例如 [if (values2[i] == "First Name")]

但是当我直接比较它们时,我在 IF 上得到一个 FALSE。我不明白...

我尝试使用字符串过滤器,但没有运气:(

这是一个非常简单的问题,很抱歉浪费您的时间,但我非常感谢您的帮助。下面的代码

 function Messagebox2() {
 var spreadsheet = SpreadsheetApp.getActive();

 var sheet = SpreadsheetApp.getActive().getSheetByName("Comments");


var range = sheet.getRange("Comments!B2:B");
var values = range.getValues();
var values2 = values.filter(String);
var range2 = sheet.getRange("Dashboard!A1")
var rowd = range2.getValues();
var rowd2 = rowd.filter(String);

   
for (var i = 0; i < values2.length; i++) {
  
 if (values2[i] == rowd2) {
var k = values2[i]

  }
  }

  Logger.log(values2[0] + "   " + k +"    " + rowd2);
}
 

输出是“名字” 未定义的 “名字”

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


The issue comes from the fact that you're comparing arrays of strings instead of the values inside them. sheet.getRange().getValues() returns an array in the form [[column1, column2, ...], ...], even if you only have one column. So the two arrays you're using are similar to the following:

values2 = [["First Name"], ["Second Name"], ...]
rowd = [["First Name"]]

So to make your code work, just change the if statement:

if (values2[i][0] == rowd2[0][0]) {
  var k = values2[i][0]
}

Next time, I would suggest logging the variables individually before you compare them to see if their values are what you think they are. Logging arrays alongside strings converts the arrays into strings, which is why you can't see the brackets in your own log. You can also use typeof.


推荐阅读