列表<字符串>语法错误谷歌脚本

List<String> Syntax error google script

本文关键字:谷歌 错误 脚本 语法 字符串 列表      更新时间:2023-09-26

我无法理解在Google脚本(基于Javascript)中设置数组。

我在数组中有一个我需要的国家/地区"AU"和"NZ"列表,稍后将添加到该列表。稍后我需要搜索数组以检查字符串是否与数组中的值匹配。

我尝试在谷歌脚本中以多种方式添加数组。

第一次尝试:

List<String> country_list = new ArrayList<String>();
country_list.add("AU");
country_list.add("NZ");

这会在第 1 行抛出一个Syntax error.

对此的变体:

第二次尝试:

var country_list = [];
country_list.add("AU")
country_list.add("NZ")

第二行抛出错误TypeError: Cannot find function add in object .

第三次尝试:

var Country_List = ["AU","NZ"];
if (country_list.contains("AU")) {
    // is valid
    ui.alert("great success");
} else {
    // not valid
    ui.alert('Nope try again');
}

这将引发错误"类型错误:找不到对象中包含的函数..."

这是有道理的,所以我尝试转换为Array.asList().

第四次尝试:

var original_country_list = ["AU","NZ"];
List<String> country_list = Arrays.asList(original_country_list)
if (country_list.contains("AU")) {
    // is valid
    ui.alert("great sucsess");
} else {
    // not valid
    ui.alert('Nah Mate try again');
}

这会引发错误Invalid assignment left-hand side,当使用 []() 来保持original_country_list 。使用 {} 按住original_country_list时,它会抛出错误Missing : after property ID

我尝试的最后一件事是:

第五次尝试:

var original_country_list = ["AU","NZ"];
var country_list = Arrays.asList(original_country_list)

这会抛出错误ReferenceError: "Arrays" is not defined.

抱歉,如果这很明显,但这里出了什么问题?

我在这里看到的大部分内容看起来更接近Java而不是Javascript。但是#2可以是这样的Javascript:

var country_list = [];
country_list.push("AU");
country_list.push("NZ");

3也可以轻松修复:

var Country_List = ["AU","NZ"];
if (Country_list.indexOf("AU") > -1) {
  // is valid
  ui.alert("great success");
 } else {
   // not valid
   ui.alert('Nope try again');
 }