function NumStuff(num) {
this.num = num;
this.multipleOfFour = function() {
//if multiple of 4
if (this.num % 4 === 0) {
console.log(this.num + " is a multiple of Four");
console.log("the structure of the given integer " +
this.num + " is ");
for (let i = 0; i < this.num; i++) {
if (4 * i === this.num) { //why is this.num outside of
//lexical scope
console.log(this.num + " = " + i + " x 4");
break;
}
}
//if not a multiple of 4
} else {
console.log(this.num + " isn't a multiple of 4 but here is the integer's structure:");
let remainder = this.num % 4;
let tempNum = this.num - remainder;
for (let i = 0; i < tempNum; i++) {
if (4 * i === tempNum) {
console.log(this.num + " = " + i + " x 4 + " + remainder);
break;
}
}
}
};
}
let num = prompt("Enter an integer:");
let n = new NumStuff(num);
n.multipleOfFour();
假设我们输入 20 作为我们的数字。它通过 multipleOfFour() 并在有条件的情况下命中第一个。this.num(20) % 4 等于 0 所以它通过了。然后我们循环遍历 i 来找出 4 乘以 20 的次数。 this.num 在 for 语句的范围内,但不在 for 语句的范围内for 语句的内部 if 条件。为什么会这样?
它在范围内。这不是问题。
但是this.num
是一个string
(prompt
总是返回的)4 * i
而是一个number
。而且4 * i === this.num
将永远是假的,无论你输入什么提示时。
试试这个(这里):
for (let i = 0; i < this.num; i++) {
console.log('x', 4 * i, this.num, 4 * i === this.num);
一个简单的解决方法是let num = parseInt(prompt("Enter an integer:"));
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句