javascript - Why can't the function foo(x = x+1){ }; parameter be x=x+1?
伊谢尔伦
伊谢尔伦 2017-05-19 10:44:17
0
3
586

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

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(3)
漂亮男人
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.

洪涛

/a/11...

Peter_Zhu

Of course not, I can do it if you want

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template