如何在函数中传递动态数量的参数
How to pass dynamic amount of arguments in function
我尝试在不同情况下传递不同数量的参数。
我有下一个代码:
function getByteCode(tokenData, incomeData){
incomeData.volume = Number(incomeData.volume) * Math.pow(10,tokenData.decimals);
incomeData.volume = incomeData.volume.noExponents();
let web3 = new Web3();
let instanceContract = new web3.eth.Contract(abi);
instanceContract.options.address = tokenData.address;
let necessaryMethod = instanceContract.methods[incomeData.methodCall];
let methodCall = necessaryMethod(incomeData.destination_address, incomeData.volume);
return methodCall.encodeABI();
} catch (err) {
sails.log(err);
return {
state: 'fail',
message: 'There is error in creation byte code \n' + err
}
}
}
在 necessaryMethod 中,我想在一种情况下传递两个参数,在另一种情况下传递三个或更多参数。我该怎么做?也许我应该使用“arguments”,但我不明白如何使用?
好的,谢谢你的帮助。我使用了方法 .apply()
let web3 = new Web3();
let instanceContract = new web3.eth.Contract(abi);
instanceContract.options.address = tokenData.address;
let necessaryMethod = instanceContract.methods[incomeData.methodCall];
let methodCall = necessaryMethod.apply(this, incomeData.argumentsForFunction);
return methodCall.encodeABI();
在第一种情况下,我调用了函数 getByteCode(firstObj, incomeData) 并且在 incomeData.argumentsForFunction = ['0x323.....', ' 1500000000'].
在其他情况下,我调用了函数 getByteCode(firstObj, incomeData) incomeData.argumentsForFunction = ['0x323......', '0x3228.... ', '54454000000']
我尝试在不同情况下传递不同数量的参数。 我有下一个代码:
function getByteCode(tokenData, incomeData){
incomeData.volume = Number(incomeData.volume) * Math.pow(10,tokenData.decimals);
incomeData.volume = incomeData.volume.noExponents();
let web3 = new Web3();
let instanceContract = new web3.eth.Contract(abi);
instanceContract.options.address = tokenData.address;
let necessaryMethod = instanceContract.methods[incomeData.methodCall];
let methodCall = necessaryMethod(incomeData.destination_address, incomeData.volume);
return methodCall.encodeABI();
} catch (err) {
sails.log(err);
return {
state: 'fail',
message: 'There is error in creation byte code \n' + err
}
}
}
在 necessaryMethod 中,我想在一种情况下传递两个参数,在另一种情况下传递三个或更多参数。我该怎么做?也许我应该使用“arguments”,但我不明白如何使用?
好的,谢谢你的帮助。我使用了方法 .apply()
let web3 = new Web3();
let instanceContract = new web3.eth.Contract(abi);
instanceContract.options.address = tokenData.address;
let necessaryMethod = instanceContract.methods[incomeData.methodCall];
let methodCall = necessaryMethod.apply(this, incomeData.argumentsForFunction);
return methodCall.encodeABI();
在第一种情况下,我调用了函数 getByteCode(firstObj, incomeData) 并且在 incomeData.argumentsForFunction = ['0x323.....', ' 1500000000'].
在其他情况下,我调用了函数 getByteCode(firstObj, incomeData) incomeData.argumentsForFunction = ['0x323......', '0x3228.... ', '54454000000']