我有这种情况,我想在对象解构时多次使用相同的变量名:
let {body, response} = await requestp('get', `${cdtAPIUrl}/whitelist`, headers);
let parsedBody = await siamese.parse(body);
assert(parsedBody.success, 'response body should have a success property.');
assert(parsedBody.success.length === usernames.length, 'wrong number of items in response body array.');
let {body, response} = await requestp('get', `${cdtAPIUrl}/caches/whitelist`, headers);
let parsedBody = await siamese.parse(body);
但是当我用节点运行脚本时,node会在运行时之前抱怨:
SyntaxError: Identifier 'body' has already been declared
有两个问题阻止我得到一个简单的解决方案:
我不能通过对象解构来做到这一点:
let {a,b} = c;
{a,b} = c; // not allowed
我无法重命名body
或response
,因为这是通话所返回的内容。
我该怎么办?
也许最好的办法是:
let {body,response} = ...
let {body:body1, response:resp1} = ...
答案 0 :(得分:2)
我无法通过对象解构来实现这一点:
{a,b} = c;
您可以,只需要put it in parenthesis to be syntactically valid:
({a, b} = c);
也许最好的办法就是
let {body:body2, response:resp2} = …
是的,这确实是最好的解决方案。您甚至可能希望使用const
代替let
。
我该怎么办?
另一个解决方案,我不一定会建议但只是想提及完整性,是为变量引入单独的范围:
{
let {body, response} = await requestp('get', `${cdtAPIUrl}/whitelist`, headers);
let parsedBody = await siamese.parse(body);
assert(parsedBody.success, 'response body should have a success property.');
assert(parsedBody.success.length === usernames.length, 'wrong number of items in response body array.');
}
{
let {body, response} = await requestp('get', `${cdtAPIUrl}/caches/whitelist`, headers);
let parsedBody = await siamese.parse(body);
}
当然,您也可以使用var
代替let
,而不是重新声明。