search

Home  >  Q&A  >  body text

javascript - Why can't the function foo(x = x+1){ }; parameter be x=x+1?

example:

let x = 99;
function foo(p = x + 1) {
  console.log(p);
}

foo() // 100

x = 100;
foo() // 101

However, if I change the parameters slightly to:

let x = 99;
function foo(x = x + 1) {
  console.log(x);
}

foo() // NaN

x = 100;
foo() // NaN

Why is it displayed as NaN? What invisible changes occurred in the middle? If you know, can you tell me? Thanks

伊谢尔伦伊谢尔伦2780 days ago594

reply all(3)I'll reply

  • 漂亮男人

    漂亮男人2017-05-19 10:46:17

    let x = 99;
    function foo(p = x + 1) {
      console.log(p);
    }
    
    // 相当于
    let x = 99;
    function foo () {
        let p;
        p = x + 1;
        console.log(p); // -> 100
    }

    The following code is equivalent to

    let x = 99;
    function foo(x = x + 1) {
      console.log(x);
    }
    // 相当于
    let x = 99;
    function foo() {
      let x;  // 此时x = undefined;
      x = undefined + 1;
      console.log(x); // -> NaN
    }

    That is to say, the x in foo(x = x + 1) has nothing to do with the x outside. It is defined inside the function by you.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:46:17

    /a/11...

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-19 10:46:17

    Of course not, I can do it if you want

    reply
    0
  • Cancelreply