前端面试题

Javascript问题集锦

  1. 对象字面值不能正常解析

    问题:

     {a:1}.a;//Uncaught SyntaxError:Unexpected token

    解决:

     ({a:1}).a;
     ({a:1}.a)

    原因:

    An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.

  2. 数字的点操作符

    问题:

     123.toFixed(2); //Uncaught SyntaxError: Unexpected token ILLEGAL

    解决:

     (123).toFixed(2);
     //以下两种都可以,不推荐
     123..toFixed(2);
     123 .toFixed(2)

    原因:

    js解析器把数字后的当作小数点而不是点操作

  3. 连续赋值问题

    问题:尝试解释下连等赋值的过程

     var a = {n:1};
     var b = a;
     a.x = a = {n:2};
     console.log(a.x); //undefined
     console.log(b.x); //{n:2}

    原因:

    1. 执行顺序。a.x = a = {n:2}相当于是a.x = (a = {n:2}),也就是先执行a = {n:2},再执行a.x = {n:2};

    2. 执行时,a.x和a的指向都是对象{n:1}【关键】

来源

  1. https://github.com/creeperyang/blog/issues/2

results matching ""

    No results matching ""