[英]Comparing array values in Google Apps script
I feel that the following two functions should produce the same result, but function bob()
never finds name1
equal to name2
, even though the names in those cells are indeed equal. 我觉得以下两个函数应该产生相同的结果,但是函数bob()
永远不会找到与name2
相等的name1
,即使这些单元格中的名称确实相等。
The function bob2()
works fine, but I'm trying to speed things up by using arrays. 函数bob2()
可以正常工作,但是我试图通过使用数组来加快速度。
function bob()
{
var ss = SpreadsheetApp.getActiveSheet();
var name1 ;
var name2 ;
var AthName = ss.getRange(1,2,30).getValues();
for (var xx=1; xx<30 ;xx++)
{
name1=AthName[xx]
name2=AthName[xx+1]
//name1 never equals name2 here.
if (name1==name2) ss.getRange(xx,10).setValue(name2);
}
}
function bob2()
{
var ss = SpreadsheetApp.getActiveSheet();
var name1 ;
var name2 ;
for (var xx=1; xx<30 ;xx++)
{
name1 = ss.getRange(xx,2).getValue();
name2 = ss.getRange(xx+1,2).getValue();
//name1 does equal name2 here as expected.
if (name1==name2) ss.getRange(4+xx,10).setValue(name2);
}
}
What's wrong with bob()
? bob()
什么问题?
The problem with bob()
is that you're setting AthName
to a two-dimensional list of values: bob()
的问题在于,您正在将AthName
设置为二维值列表:
var AthName = ss.getRange(1,2,30).getValues();
Range.getValues()
always returns a two-dimensional list indexed by row and column. Range.getValues()
始终返回按行和列索引的二维列表。
This means that you're assigning lists to name1
and name2
: 这意味着您正在将列表分配给name1
和name2
:
name1=AthName[xx]
name2=AthName[xx+1]
Lists are equal only when they're the same list, ie , the variables refer to the same memory location. 列表仅在相同列表时才相等, 即 ,变量引用相同的内存位置。 So name1 == name2
is going to be false no matter what the lists contain. 因此,无论列表包含什么内容, name1 == name2
都将为false。
The fix is probably evident to you by now. 该修复程序现在可能对您很明显。 Retrieve the value from each row: 从每一行检索值:
name1 = AthName[xx][0];
name2 = AthName[xx+1][0];
(I've added spaces and semicolons for the sake of good JavaScript style.) (为了获得良好的JavaScript样式,我添加了空格和分号。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.