javascript - 将简写 JS 添加到父级

标签 javascript json google-apps-script

我正在创建一些速记 js 变量,这些变量最终将合并到父级中以创建一些 XML。我的速记 js 在这里做错了什么?我有点迷路了。

我想出了这个简短的例子来概述我的问题:

function testing() {
  var attachments = [];

  var attachment1 = [ "attachment" ,
                     [ "name", "myname1" ],
                     [ "type", "mytype1" ]
                    ];
  attachments.push(attachment1);
  var attachment2 = [ "attachment" ,
                     [ "name", "myname2" ],
                     [ "type", "mytype2" ]
                    ];
  attachments.push(attachment2);

  var email = [ "email",
               [ "subject", "mySubject"],
               [ "body", "myBody"],
               [ "attachments", attachments ]
              ];
  Logger.log(Xml.parseJS(email).toXmlString());
}

日志输出:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<email>
    <subject>mySubject</subject>
    <body>myBody</body>
    <attachments>[Ljava.lang.Object;@b06f679</attachments>
</email>

理想情况下,它应该是:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<email>
    <subject>mySubject</subject>
    <body>myBody</body>
    <attachments>
        <attachment>
            <name>myname1</name>
            <type>mytype1</type>
        </attachment>
        <attachment>
            <name>myname2</name>
            <type>mytype2</type>
        </attachment>
    </attachments>
</email>

最佳答案

您正在将一个数组放在一个数组中。

var attachment1 = [ "attachment" ,
                   [ "name", "myname1" ],
                   [ "type", "mytype1" ]
                  ];

var attachment2 = [ "attachment" ,
                   [ "name", "myname2" ],
                   [ "type", "mytype2" ]
                  ];


var email = [ "email",
             [ "subject", "mySubject"],
             [ "body", "myBody"],
             [ "attachments"]
            ];
email[3].push(attachment1);
email[3].push(attachment2);

您可以使用 console.log(email) 查看网络浏览器结构的不同

这也会让同样的事情更具可读性

attachments = ["attachments"];
attachments.push(attachment1);
attachments.push(attachment2);
var email = [ "email",
              [ "subject", "mySubject"],
              [ "body", "myBody"],
              attachments
            ];

关于javascript - 将简写 JS 添加到父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12647996/

相关文章:

javascript - Kendo UI 中添加记录功能,始终插入两行

iphone - iPhone 上什么速度更快? XML pList 还是 JSON?

javascript - 将 Javascript 变量传递给 Google 脚本函数 (Google Sheets)

google-apps-script - 提供 API key 以避免 Apps 脚本中的 map 服务出现命中限制错误

javascript - 仅当用户未将鼠标悬停在另一个类上时才单击功能

javascript - 无法显示已存在的文件 jQuery 文件 uploader

javascript - VueJs 模块构建失败 : Error: Couldn't find preset "@vue/app" relative to directory

json - Serilog.Sinks.Postgresql : Read configuration from appsettings. json

ruby - 如何将 JSON 转换为 Ruby 哈希

javascript - 通过 Drive API 自动执行 Google Sheet 操作(制作副本、Google App 脚本、触发器)