[英]Global variable of JavaScript function
The problem is, that my function doesnt return the correct value. 问题是我的函数没有返回正确的值。 I think the reason is, because the callback is loaded after the value is returned. 我认为原因是因为在返回值之后加载了回调。
The code: 编码:
function hexToBase58(inputNumber) {
var output = "";
$.getScript("JavaScript/biginteger.js", function(){
//hexToDecimal
var sum = new BigInteger();
for (var i = 0;i<inputNumber.length;i++)
{
sum = sum.multiply(new BigInteger(16)).add(new BigInteger(hexToDecimalChar(inputNumber.charAt(i))));
}
//decimalToBase58
var rest = new Array();
var base = new BigInteger(58);
var i = 0;
do
{
rest[i] = sum.remainder(base).valueOf();
sum = sum.divide(base);
i++;
}while(sum.valueOf() > 0)
for(var j=0;j<i;j++)
{
output = output + decimalToBase58Char(rest[i-j-1]);
}
console.log(output);
});
console.log(output);
return output;
}
I get two outputs: 我得到两个输出:
"output" is a global variable but the function does not return the second string but the first one. “输出”是一个全局变量,但是该函数不返回第二个字符串,而是第一个字符串。 I dont know how to return the value from the inner function to the outer one. 我不知道如何从内部函数返回值到外部函数。
It is very late and I tried a lot. 已经很晚了,我尝试了很多。 I think maybe ajax can help. 我认为也许ajax可以提供帮助。 But I have no experience with ajax. 但是我没有使用ajax的经验。
Don't load the script using $.getScript
, but simply with a <script>
tag. 不要使用$.getScript
加载脚本,而只需使用<script>
标记即可。
<script src="JavaScript/biginteger.js"></script>
Then your function can be without the get script part: 然后,您的函数可以没有get脚本部分:
function hexToBase58(inputNumber) {
var output = "";
//hexToDecimal
var sum = new BigInteger();
for (var i = 0;i<inputNumber.length;i++)
{
sum = sum.multiply(new BigInteger(16)).add(
new BigInteger(hexToDecimalChar(inputNumber.charAt(i))));
}
//decimalToBase58
var rest = new Array();
var base = new BigInteger(58);
var i = 0;
do
{
rest[i] = sum.remainder(base).valueOf();
sum = sum.divide(base);
i++;
}while(sum.valueOf() > 0)
for(var j=0;j<i;j++)
{
output = output + decimalToBase58Char(rest[i-j-1]);
}
return output;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.