我有两个功能:
var number1 = 9
var number2 = 17;
//Get Percent of a the number1
function getPercent(x, y) {
return x * 100 / y;
}
var percentOfNumber1 = getPercent(number1, number2);
//Get rid of remainder
function getRemain(t) {
var remainder = t % 2;
t = t - remainder;
return t;
}
alert(getRemain(percentOfNumber1));
有效..但我想在第一个函数中关闭getRemain函数。
所以我做了什么,我不会得到结果:
function getPercent(x, y) {
return x * 100 / y;
function getRemain(t) {
var remainder = t % 2;
t = t - remainder;
return t;
}
var numberClear = getRemain(result);
}
var result = getPercent(number1, number2);
alert(numberClear);
任何人都可以解释错误的做法吗? “这是我第一次尝试关闭时,我读了几个很好的解释,但是我觉得调用函数部分不是很好......” 日Thnx。
答案 0 :(得分:2)
如果您想在外面访问,请在外面声明numberClear
:
var numberClear;
function getPercent(x, y) {
function getRemain(t) {
return t - t % 2;
}
var result = x * 100 / y;
numberClear = getRemain(result);
return result;
}
var result = getPercent(number1, number2);
alert(numberClear);
答案 1 :(得分:1)
为什么不呢?
一次返回两个值
function getPercentage(a, b){
function getRemain(t)
{
var remainder = t % 2;
t = t - remainder;
return t;
}
return {
percentage: a / b * 100,
remain: getRemain(a / b * 100)
}
};
var result = getPercentage(9, 17);
alert(result.percentage);
alert(result.remain);
答案 2 :(得分:0)
您根本没有正确返回结果:
function getPercent(x,y)
{
function getRemain(t)
{
var remainder = t % 2;
t = t - remainder;
return t;
}
return getRemain(x * 100 / y); // <-- return what getRemain() gives you!
}
var result = getPercent(number1, number2);
答案 3 :(得分:0)
无法从外部访问函数内声明的变量。
你可以试试这个:
var getPercent = (function() {
function getRemain(t)
{
var remainder = t % 2;
t = t - remainder;
return t;
}
return function (x,y)
{
var percent = x * 100 / y;
return {
percent: percent,
remainder: getRemain(percent)
};
}
})();
这样,getRemain
函数无法访问,getPercent
函数将返回百分比和余数值。
答案 4 :(得分:0)
试试这个
var numberClear;
function getPercent(x, y) {
var percentange = x * 100 / y;
numberClear = getRemain(result); // set your numberClear Variable here
return percentange;
}
function getRemain(t) {
return t - t % 2;
}
var result = getPercent(number1, number2);
alert(numberClear);