V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
mufeng
V2EX  ›  JavaScript

为什么 eval for 循环会有返回值

  •  
  •   mufeng · 2017-07-11 17:38:09 +08:00 · 2109 次点击
    这是一个创建于 2472 天前的主题,其中的信息可能已经有所发展或是发生改变。

    https://ws2.sinaimg.cn/large/6115ac8fgy1fhg2y5ckgoj20ts04474u.jpg

    timwei
        1
    timwei  
       2017-07-11 17:50:51 +08:00   ❤️ 1
    push method returns object's length
    timwei
        2
    timwei  
       2017-07-11 17:51:49 +08:00
    mufeng
        3
    mufeng  
    OP
       2017-07-11 17:53:42 +08:00
    @timwei #1 谢谢
    autoxbc
        4
    autoxbc  
       2017-07-11 18:28:40 +08:00   ❤️ 2
    就这个题目来说,单看 push 的返回值并不算完。关键的部分是,ECMA 详细规定了块语句的返回值,for 循环的返回值,可以看这个文档。

    http://www.ecma-international.org/ecma-262/6.0/index.html#sec-for-statement
    timwei
        5
    timwei  
       2017-07-12 12:32:13 +08:00   ❤️ 1
    @autoxbc 感谢回复,不过我认为与文件的 for 实现无关


    TL; DR
    ```
    value = eval('for(let a=0 ; a<9 ; a++){arr=[];arr.push(""); };'); //lz 的题目
    value
    // 1
    //这个 1 是因为 eval() 返回了 for 最后的执行语句 arr.push("")
    //而 arr.push("")返回了阵列的长度。
    ```

    与文件中的 for 规定的返回值无关,倒是与执行顺序有关。
    http://www.ecma-international.org/ecma-262/6.0/index.html#sec-forbodyevaluation

    for 不帶 Return value 的
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

    举例来说,就是你"不能"写些像

    ```
    value = for(let a=0 ; a<1 ; a++){ a };

    ```

    会有输出是因为 eval(),eval()会 return 最后一个执行的 statement
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

    ```
    eval(1; 2; 3;)
    // 3

    value = eval('for(let a=0 ; a<9 ; a++){arr=[];arr.push(""); }; 5566;');
    // 5566
    // #其实 for 跟 push 都是伪命题
    ```
    mufeng
        6
    mufeng  
    OP
       2017-07-12 12:33:55 +08:00
    @timwei 是的,作用块的返回值
    autoxbc
        7
    autoxbc  
       2017-07-12 21:15:14 +08:00   ❤️ 1
    @timwei 在规范中似乎每种类型的语句都有一个明确的返回结果,不过从不能赋值存储看确实不是我说的返回值。

    能看到输出结果的关键确实是 eval,或者说是 REPL。
    mufeng
        8
    mufeng  
    OP
       2017-07-13 09:01:25 +08:00   ❤️ 2
    @autoxbc #7
    @timwei #5
    https://twitter.com/paul_irish/status/818568243350630401 有关于 statement completion value 的讨论
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4993 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 05:39 · PVG 13:39 · LAX 22:39 · JFK 01:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.