gpt4 book ai didi

javascript - 将简写 JS 添加到父级

转载 作者:行者123 更新时间:2023-11-29 10:49:48 25 4
gpt4 key购买 nike

我正在创建一些速记 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com