所以我有以下代码:
async function runQuery(input)
{
return input
}
async function createAccounts()
{
return [1, 2]
}
(async function ()
{
var
creator1_ids =
{},
creator2_ids =
{}
let all_accounts =
await createAccounts(2)
const tables =
[
"list",
"display_list",
"map"
]
for (let index in all_accounts)
{
let req =
{
session:
{
account:
null
}
}
req.session.account =
all_accounts[index]
let the_ids =
index === 0
? creator1_ids
: creator2_ids
// Create item
let result =
await runQuery()
the_ids.item =
1
for (let table of tables)
{
result =
await runQuery(table)
the_ids[table] =
result
}
}
console.log(creator1_ids)
console.log(creator2_ids)
})()
现在javascript将对象用作引用(因此,如果将另一个变量分配给一个对象,更改其中一个变量将更改整个对象),但是这里似乎不是这种情况。
creator1_ids
保持空白,而仅填充creator2_ids
。我希望creator1_ids
的填充方式与此类似。
但这可行。
async function runQuery(input)
{
return input
}
async function createAccounts()
{
return [1, 2]
}
(async function ()
{
var
creator1_ids =
{},
creator2_ids =
{}
let all_accounts =
await createAccounts(2)
const tables =
[
"list",
"display_list",
"map"
]
async function generate(the_ids, account)
{
let req =
{
session:
{
account:
null
}
}
// Create item
let result =
await runQuery()
the_ids.item =
1
for (let table of tables)
{
result =
await runQuery(table)
the_ids[table] =
result + account
}
}
await generate(creator1_ids, all_accounts[0])
await generate(creator2_ids, all_accounts[1])
console.log(creator1_ids)
console.log(creator2_ids)
})()
答案 0 :(得分:3)
该结论无效,因为调试存在缺陷。在调试器中仔细查看,特别是在此行上:
let the_ids =
index === 0 ?
creator1_ids :
creator2_ids
index
从不等于0
。 确实等于'0'
。因此===
永远不会是true
。
更改比较,您将获得期望的结果:
let the_ids =
index == 0 ? // compare values regardless of type
creator1_ids :
creator2_ids
然后,您的循环将首先修改creator1_ids
,然后修改creator2_ids
。演示:
async function runQuery(input) {
return input
}
async function createAccounts() {
return [1, 2]
}
(async function() {
var creator1_ids = {},
creator2_ids = {}
let all_accounts = await createAccounts(2)
const tables = [
"list",
"display_list",
"map"
]
for (let index in all_accounts) {
let req = {
session: {
account: null
}
}
req.session.account = all_accounts[index]
let the_ids =
index == 0 ?
creator1_ids :
creator2_ids
// Create item
let result = await runQuery()
the_ids.item = 1
for (let table of tables) {
result = await runQuery(table)
the_ids[table] = result
}
}
console.log(creator1_ids)
console.log(creator2_ids)
})()
答案 1 :(得分:2)
索引是字符串,因此请使用引号。见下文
let the_ids = index === '0'? creator1_ids : creator2_ids
代替
let the_ids = index === 0 ? creator1_ids: creator2_ids