[英]Comparing values in an array (app script)
first I'm new to Apps Script respectively Javascript. However in Google Sheets with Apps Script I have filled an array with the contents of one column.首先,我分别是 Apps Script 的新手 Javascript。但是在带有 Apps Script 的 Google 表格中,我用一列的内容填充了一个数组。 Now I would like to find matching values in this array.
现在我想在这个数组中找到匹配的值。 I tried the following code with a simple array like [2,5,3,6,2,7] and the code works.
我用 [2,5,3,6,2,7] 之类的简单数组尝试了以下代码,并且代码有效。 It doesn't work though with the values from the column (eg something like '110rt' or '38tzu0'):
它不适用于列中的值(例如“110rt”或“38tzu0”):
let z = sheet.getRange("D2:D" + sheet.getLastRow())
let a = z.getValues()
for (let i = 0; i < a.length; i++) {
for (let k = i + 1; k < a.length; k++) {
if (a[i] == a[k]) {
console.log("hit")
}
}
} }
So in the above code the if clause never becomes true and I don't understand why.所以在上面的代码中,if 子句永远不会变为真,我不明白为什么。
When you use getRange
with multiple rows, it returns each row in a seperate sub-array.当您对多行使用
getRange
时,它会在单独的子数组中返回每一行。 The end result is a 2D array, where each sub-array represent a row.最终结果是一个二维数组,其中每个子数组代表一行。
For example:例如:
[
[A1,B1,C1,...],
[A2,B2,C2,...],
[A3,B3,C3,...]
]
In your case, where you have only one column, it looks like that:在您的情况下,您只有一列,它看起来像这样:
[[2 ],[5 ],[3 ],[6 ],[2 ],[7]]
[[D2],[D3],[D4],[D5],[D6],[D7]] // the matching cells
The buttom line is that you need to iterate a[k][0]
and a[i][0]
底线是你需要迭代
a[k][0]
和a[i][0]
let z = sheet.getRange("D2:D" + sheet.getLastRow())
let a = z.getValues()
for (let i = 0; i < a.length; i++) {
for (let k = i + 1; k < a.length; k++) {
if (a[i][0] == a[k][0]) {
console.log("hit")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.