如何在 Google Apps Script 中使用 Dictionary javascript 类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14074217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use the Dictionary javascript class in Google Apps Script?
提问by user1935166
I am trying to make and use a Dictionary object in Google Apps Script. Before, I used a very long switch statement for my script the first time around, and when I submitted it to the Gallery, the person who approved it asked why I didn't use a Javascript Dictionary object instead. I looked into how to use Dictionary objects, but now my script wont' work because Google Apps Script doesn't understand the command:
我正在尝试在 Google Apps Script 中创建和使用 Dictionary 对象。之前,我第一次在我的脚本中使用了很长的 switch 语句,当我将它提交给 Gallery 时,批准它的人问我为什么不使用 Javascript Dictionary 对象来代替。我研究了如何使用 Dictionary 对象,但现在我的脚本无法运行,因为 Google Apps 脚本不理解命令:
Components.utils.import("resource://gre/modules/Dict.jsm");
This 'import' line of code was copied straight from this Javascript Reference webpage: http://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Dict.jsm
这行“导入”代码直接从这个 Javascript 参考网页复制而来:http: //developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Dict.jsm
How do I include this javascript library needed to make it work, or what is the Google Apps Script alternative to a javascript Dictionary object?
我如何包含使其工作所需的这个 javascript 库,或者什么是 javascript Dictionary 对象的 Google Apps Script 替代方案?
回答by Pointy
Any time you've got a switch
statement that looks something like:
任何时候你有一个switch
看起来像这样的语句:
switch ( someValue ) {
case "string1": doSomething( valueForString1 ); break;
case "string2": doSomething( valueForString2 ); break;
// ...
case "stringN": doSomething( valueForStringN ); break;
}
you can replace that with:
您可以将其替换为:
var dict = {
"string1": valueForString1,
"string2": valueForString2,
// ...
"stringN": valueForStringN
};
doSomething( dict[ someValue ] );
The values can be anything, of course: strings, numbers, objects, functions, whatever. And you probably would want to check for a value being missing from the dictionary:
当然,值可以是任何东西:字符串、数字、对象、函数等等。您可能想要检查字典中是否缺少某个值:
if (dict[someValue]) doSomething(dict[someValue]);