使用Google表格脚本,为什么我的if语句在比较单元格值时总是返回false? [英] Using Google Sheets scripts, why does my if statement always return false when comparing cell values?
问题描述
我需要比较两个单元格值,如果它们不同,请对它们进行操作.比较单元格内容时,我的"if"语句始终返回false,但我不知道为什么:
I need to compare two cell values and act on them if they are different. My "if" statement always returns false when comparing the cell contents however, and I can't figure out why:
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1'); // apply to sheet name only
var testvalues = sheet.getRange('A1:A2').getValues(); // array of values to be tested
var testvalue1 = testvalues[0]; // The contents from A1
var testvalue2 = testvalues[1]; // The contents from A2
var test1 = testvalue1 == testvalue2; // True False test
var test2 = testvalue1 === testvalue2;// True False test
Browser.msgBox(testvalue1 + " and " + testvalue2 + " being the same is " + test1 + " and " + test2); // Sentence revealing outcome
};
无论单元格A1和A2的内容是什么(空,数字,文本,不同),
test1和test2始终返回false.如果我将测试值编辑为此:
test1 and test2 always return false no matter what the contents of cell A1 and A2 are (empty, number, text, different). If I edit the testvalues to this:
var testvalue1 = "We are the same value";
var testvalue2 = "We are the same value";
或
var testvalue1 = testvalues[0];
var testvalue2 = testvalues[0];
然后突然,两个测试都按预期返回True.谁能告诉我我在这方面所缺少的,那太令人生气了吗?当前在A1和A2中的值为1(在我可能被问到这一点之前).
then suddenly the tests both return True as expected. Can anyone tell me what I'm missing in this, it's infuriating? Currently in A1 and A2 is the value 1 (before I potentially get asked about that).
最终目标是使用边框划分不同的单元格内容.我的其余部分都可以正常工作,但我已将问题与上述概念隔离了.
The end goal is to use a border to partition different cell contents. I have the rest of it working perfectly but I've isolated the problem to the above concept.
非常感谢您的帮助!
推荐答案
答案:
.getValues()
方法返回一个二维数组,因此您没有在数组中正确引用每个单元格中的值.
Answer:
The .getValues()
method returns a 2-dimensional array, and so you aren't referencing the values within each cell correctly in your array.
我们假设A1
和A2
都包含字符串"THIS"
.
运行以下行:
Let's assume that both A1
and A2
contain the string "THIS"
.
Running the following line:
var testvalues = sheet.getRange('A1:A2').getValues();
会将数组[[THIS], [THIS]]
分配给testvalues
.
您需要更改:
var testvalue1 = testvalues[0]; // The contents from A1
var testvalue2 = testvalues[1]; // The contents from A2
收件人:
var testvalue1 = testvalues[0][0]; // The contents from A1
var testvalue2 = testvalues[1][0]; // The contents from A2
希望对您有帮助!
- Class
Range
| Apps Script - MethodgetValues()
这篇关于使用Google表格脚本,为什么我的if语句在比较单元格值时总是返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!