Google Apps 脚本在数组中查找值

Dan*_*ard 5 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()
 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);
}
Run Code Online (Sandbox Code Playgroud)

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

Vyt*_*tas 4

我注意到你提到玩家是第 7 列。请注意,你实际检查的是

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

并且永远不要真正触摸除第一列之外的任何列,因为您已经[0]if(playerNameValues[n][0]== findPlayer) {break}. 相反,这样做(我假设你已经var i这样做了var n

for (i = 0; i < playerNameValues.length; i++) {
  for (n = 0; n < playerNameValues[i].length; n++) {
    if (playerNameValues[i][n] == findPlayer) break
  }
  if (playerNameValues[i][n] == findPlayer) break
}
Run Code Online (Sandbox Code Playgroud)

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