您正在处理两个不同的currpage
变量,undefined
当您尝试对其执行算术运算时导致其中一个变量出现,从而产生NaN
结果。请参阅下面的内联代码注释以获取更多说明:
$(document).ready(function() {
var currpage=1; // Local to this function, because of the var keyword.
...
})
}) // I'm assuming this extra closing brace and paren is a typo.
// Otherwise, your code example has a syntax error or is incomplete.
function passfrom(currpage) {
// currpage is the name of the parameter to passfrom.
// It happens to have the same name as a local var in
// the document.ready callback above, but the two are
// not the same.
var newpage = parseInt(currpage)*1000;
return newpage;
}
function passto() {
// passfrom is called with an implicit 'undefined' argument.
// Thus, undefined will be used in the arithmetic ops and produce NaN.
var newcurr = passfrom();
// Don't need the var keyword below.
var newcurr = newcurr * 1000;
console.log(typeof(newcurr)); //number
return newcurr;
}
您需要使相同的currpage
变量可以从两者passfrom
中访问passto
,并将其放在更高/更多的全局范围内,或者将这些函数移动到与原始范围相同的范围内currpage
。像这样:
var currpage;
$(document).ready(function () {
$('p').click(function () {
var xyz = passfrom(1); //pass var to function and return value
console.log(xyz); //returns correct value
var abc = passto();
console.log(abc); //NaN
})
})
// Rename the param so there isn't a naming conflict.
function passfrom(currpageParam) {
// If the param is a number, reset the global var.
if (typeof currpageParam == 'number') { currpage = currpageArg; }
var newpage = parseInt(currpage) * 1000;
return newpage;
}
function passto() {
var newcurr = passfrom();
newcurr = newcurr * 1000;
console.log(typeof (newcurr)); //number
return newcurr;
}
不过要小心。您可能需要采取措施保护您的 currpage var 免受外部修改。另外,我怀疑有更好的方法来做你想做的事情,但目前还不清楚那是什么,所以我不能提出任何建议。