Google apps script Google应用程序脚本在数组中查找值

Google apps script Google应用程序脚本在数组中查找值,google-apps-script,Google Apps Script,我不知道如何检查数组中是否存在值。我认为这应该是非常简单的,但无法实现 我有以下代码: function findPlayer() { //This section gets the values from the first row of all the columns var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Players"); var lastColumn = ss.getLastColumn()

我不知道如何检查数组中是否存在值。我认为这应该是非常简单的,但无法实现

我有以下代码:

function findPlayer() {
 //This section gets the values from the first row of all the columns
 var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Players");
 var lastColumn = ss.getLastColumn()
 var playerNameRow = ss.getRange(1, 2, 1, lastColumn - 3); 
 var playerNameValues = playerNameRow.getValues(); 

 //This just sets the value we're looking for (which in this example is in the 7th Column "G"). And logs the Array, just to check it.
 var findPlayer = "Dan";
 Logger.log(playerNameValues)


 //and here we just loop through the playerNameValues array looking for the findPlayer value
 for(var n in playerNameValues){
 if(playerNameValues[n][0]== findPlayer) {break}
}

//and here, if the above search does find the matching value it should log it 
Logger.log(n);
}

发生的情况是playerNameValue记录正确,但n始终记录为0。这意味着它在检查的第一项中查找值,而不是在第7列中查找值。

我注意到您提到的播放器是第7列。请注意,您实际检查的是

第1行第1列 第2行第1列 第3行第1列

并且永远不要实际触摸除第一列之外的任何列,因为在
if(playerNameValues[n][0]==findPlayer){break}
中有
[0]
。而是这样做(我假设您已经有了
var I
var n

for(i=0;i

我们进行第二次中断来中断第二个循环,但是有更好的方法来编写代码,这只是为了说明您需要做什么。

如果行和列颠倒,请使用:

 for(var n in playerNameValues[0]){
 if(playerNameValues[0][n]== findPlayer) {break}
}
或者另一种方法是使用indexOf而不是Upper

Logger.log(playerNameValues[0].indexOf(findPlayer));

啊,这是有道理的。非常感谢!请记住,我所写的内容认为任何行和任何列都可以有播放器名称。如果播放机名称都在特定行中,则使用
.getValues()
获得的数组,然后使用
数组[行][列]
访问它们。所以,如果它们都只在第5行,那么你也可以简单地通过
array[4][col]
Ah,是的。非常清楚。谢谢。请看一下这个示例代码,特别注意getRowsData()函数下面完整代码部分的部分。这是一种将数据读入对象的方法。然后可以使用playNameValues.player[n]或标题行显示的任何内容。
Logger.log(playerNameValues[0].indexOf(findPlayer));