我正在NodeJS
var detail = await orderModels.get_rab_workitem_v2(order_id)
detail.forEach(keys => {
var beneficiary_name = keys.cp_name
var beneficiary_account = keys.bank_account_number
var beneficiary_bank = keys.iris_code
var beneficiary_email = keys.email
})
问题是,如何从forEach循环beneficiary_name
内部调用NodeJS
变量?
我的意思是我想在forEach循环之外调用beneficiary_name
变量,例如:
var detail = await orderModels.get_rab_workitem_v2(order_id)
detail.forEach(keys => {
var beneficiary_name = keys.cp_name
var beneficiary_account = keys.bank_account_number
var beneficiary_bank = keys.iris_code
var beneficiary_email = keys.email
})
var test = beneficiary_name
如何?
答案 0 :(得分:1)
当前看来您想将最后分配的值分配给beneficiary_name
。
因此,基本上,您可以跳过forEach
并仅从最后一个索引中读取值:
var detail = await orderModels.get_rab_workitem_v2(order_id);
var test = detail[detail.length - 1].cp_name;
但是,如果您想要一个key.cp_name数组,则可以使用detail.map(keys => keys.cp_name)
,也可以在正确的范围内定义一个数组并推送数据:
var beneficiary_name_list = [];
var detail = await orderModels.get_rab_workitem_v2(order_id)
detail.forEach(keys => {
var beneficiary_name = keys.cp_name
var beneficiary_account = keys.bank_account_number
var beneficiary_bank = keys.iris_code
var beneficiary_email = keys.email
beneficiary_name_list.push(keys.cp_name);
})
var test = beneficiary_name_list
答案 1 :(得分:1)
在循环外声明变量,然后在循环内设置变量,将允许您的test
Var引用受益变量...但是,循环会将受益变量设置为detail数组中的最后一个元素。如果您打算在detail
数组的每次迭代中对每个受益人变量执行某项操作,那么我建议您在循环内执行该逻辑-出于上述考虑,不要在循环外进行。
var beneficiary_name
var beneficiary_account
var beneficiary_bank
var beneficiary_email
var detail = await orderModels.get_rab_workitem_v2(order_id)
detail.forEach(keys => {
beneficiary_name = keys.cp_name
beneficiary_account = keys.bank_account_number
beneficiary_bank = keys.iris_code
beneficiary_email = keys.email
})
var test = beneficiary_name