Giter VIP home page Giter VIP logo

Comments (5)

xcatliu avatar xcatliu commented on July 21, 2024 10
undefined
11

varif 里面,会提前到块级作用域的开始,相当于:

var x;
var y = 10;

if (!(x in window)) {
  x = 10;
} else {
  ++y;
}

alert(x);
alert(y);

from frontend-interview.

VamKram avatar VamKram commented on July 21, 2024

var x = 10; -> var x ; x = 10;

from frontend-interview.

hungeroxc avatar hungeroxc commented on July 21, 2024

输出undefined和11,其中x的值为undefined,y的值为11。

原因:变量提升,对式子进行转换后得出:

 var y;
 var x;
 y = 10;
 if (!(x in window)) {
    x = 10;
 } else {
    ++y;
 }
alert(x);
alert(y);`

然后因为,此时的x在全局环境被声明,所以!(x in window)为false,不执行x的赋值,然后执行++y,得出y值为11,x值为undefined;

from frontend-interview.

pingfengafei avatar pingfengafei commented on July 21, 2024

因为js没有块级作用域,以及存在变量提升。
这里补充另一种情况:函数的变量提升:

foo(); // foo
bar(); //bar is not defined

function foo() {
  console.log('foo');
}

bar = function () {
  console.log('bar');
};

from frontend-interview.

coolHt avatar coolHt commented on July 21, 2024

学习到了。还以为没有满足条件var 不会声明提前了。get

from frontend-interview.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.