JavaScript含全局输入的类方法返回NaN问题求助
嘿,别慌!我来帮你拆解一下为什么你的函数会返回NaN——其实代码里还有个隐藏问题可能先引发错误,咱们一步步来:
问题1:method1没有成为实例的可访问方法
你在构造函数newClass里定义的method1只是一个内部私有函数,并没有把它挂载到实例的this上。这意味着你的newC实例根本找不到method1这个方法!正常情况下调用newC.method1()会直接抛出TypeError: newC.method1 is not a function的错误,可能你运行时的环境表现特殊才显示了NaN,但这是第一个要解决的核心问题。
修复方法很简单,把method1赋值给this:
function newClass(self) { this.invest; this.interest; // 将方法挂载到实例上,让外部能访问 this.method1 = function() { return this.invest + this.interest; } }
问题2:prompt()返回的是字符串,直接相加会导致非数值运算
prompt()获取到的用户输入是字符串类型,哪怕用户输入的是数字,比如输入100,实际得到的是"100"而不是数字100。如果直接用+操作符,两个字符串会被拼接(比如"100"+"5"得到"1005"),但如果用户输入了非数字内容,或者直接取消输入得到null,就会在运算时得到NaN。
所以必须把输入转换成数字类型,推荐用parseFloat()(支持整数和小数):
newC.invest = parseFloat(prompt("Enter investment")); newC.interest = parseFloat(prompt("Enter interest"));
如果想更严谨,还可以加个校验,避免无效输入导致NaN:
// 处理投资金额输入 const investInput = prompt("Enter investment"); newC.invest = !isNaN(parseFloat(investInput)) ? parseFloat(investInput) : 0; // 处理利率输入 const interestInput = prompt("Enter interest"); newC.interest = !isNaN(parseFloat(interestInput)) ? parseFloat(interestInput) : 0;
完整修正后的代码
function newClass(self) { this.invest; this.interest; this.method1 = function() { return this.invest + this.interest; } } var newC = new newClass(); const investInput = prompt("Enter investment"); newC.invest = !isNaN(parseFloat(investInput)) ? parseFloat(investInput) : 0; const interestInput = prompt("Enter interest"); newC.interest = !isNaN(parseFloat(interestInput)) ? parseFloat(interestInput) : 0; alert(newC.method1());
内容的提问来源于stack exchange,提问作者LevoDoe
相关产品推荐
相关产品推荐

