为什么如果有条件,外部变量不可用

时间:2019-02-28 15:52:30

标签: javascript if-statement scope

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的次数。此.num在for语句的范围内,但不在for语句的范围内内部,如果条件为for语句。为什么呢?

1 个答案:

答案 0 :(得分:2)

它在范围内。这不是问题。

但是this.numstring(这就是prompt 总是返回的内容),而4 * inumber。并且4 * i === this.num总是 为假,无论在提示时输入什么。

尝试一下(here):

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:"));