JavaScript数字转布尔值问题:isItHigher未返回预期布尔值求助
问题原因及解决办法
核心问题
你现在控制台输出的是Example类的实例exampleCall,根本没输出isItHigher函数的返回值,自然看不到布尔值。另外构造函数里调用isItHigher(this.books)后,没对返回值做任何处理,等于白调用。
具体问题拆解
- 你执行
console.log('exampleCall --->', exampleCall),打印的是新建的类实例,里面只有title、author、books三个属性,和isItHigher的返回结果无关 isItHigher函数的逻辑有冗余:第一个判断已经覆盖了amount>200返回true,第二个判断amount<100000000返回false,其实只要写return amount > 200就够了;而且如果amount等于200或者100000000,当前函数会返回undefined
修复方案
方案1:直接打印isItHigher的返回值
把代码改成这样:
class Example { constructor(title, author, amount) { this.title = title; this.author = author; this.books = +amount; // 直接打印函数返回结果 console.log('是否大于200:', isItHigher(this.books)); } } const exampleCall = new Example("Example Book", "Example Author", 300); function isItHigher(amount) { // 简化逻辑,直接返回判断结果 return amount > 200; }
方案2:把判断结果存到实例属性,再打印实例
class Example { constructor(title, author, amount) { this.title = title; this.author = author; this.books = +amount; // 把判断结果存为实例的一个属性 this.isHigher = isItHigher(this.books); } } const exampleCall = new Example("Example Book", "Example Author", 300); console.log('exampleCall --->', exampleCall); // 也可以单独打印判断结果 console.log('是否大于200:', exampleCall.isHigher); function isItHigher(amount) { return amount > 200; }
内容的提问来源于stack exchange,提问作者Paulius
相关产品推荐
相关产品推荐

