如何获取优化后的变量值?

问题描述 投票:0回答:4

一些变量可以在 Javascript 执行期间“优化”。因此,调试时无法检查此类变量的值(用户文档)。变量视图显示 (已优化) 消息,如果尝试评估变量,控制台会抛出以下错误:

Error: variable has been optimized out

有什么方法可以强制评估此类变量或在 Firefox 中禁用此优化吗?

javascript debugging firefox javascript-debugger
4个回答
11
投票

以阻止这种优化的方式使用变量。

function NOP() {}

// then in the optimised code

    NOP(myvar);
    // debugging here should now show `myvar`

7
投票

当变量被“优化掉”时,它仅意味着它没有在当前作用域的上下文中被修改。因此,JavaScript 引擎做了一些优化魔法,暂时隐藏了该变量。例如,假设您正在使用 lodash 来迭代某种类型的集合。

var parentThingy = [];
var childThingy = [];
_.each (collectionThingy, function(data){

    // parentThingy is not being modified inside this callback
    // so it will be "optimized away" while you are inside this
    // function scope.

    var transformed;
    if (data.someFlag) {
        transformed = transformDataSomehow(data);
    }

    // childThingy is being modified, so you will be able to
    // see its value in the debugger.

    if (transformed) {
        childThingy.push(transformed);
    }
});

// Now that you've exited the callback scope, you will be able to see
// the value of parentThingy again.

if (childThingy.length > 1){
   parentThingy.push(childThingy);
}

您可以使用 NOP 建议强制parentThingy 在回调范围内可见,但由于您没有在该回调内修改parentThingy,因此您不需要需要看到它。它没有改变,也不会改变。它与您当前正在调试的代码无关。一旦退出回调的范围,parentThingy 将再次对调试器可见。

仅供参考:这不是 Firefox 的事情。 Chrome 做了同样的事情,它只是使用不同的措辞来指示变量与当前范围无关。


2
投票

如果需要调试该变量,则必须在函数内声明该变量的位置设置断点。

假设您需要调试变量

“价值”

function(value) {
   // If you set the breakpoint somewhere here it is OK

   myArray.map(function() {

       // If you set the breakpoint here you will get an Error: variable has been optimized out

   }

} 

0
投票

当您有权访问源代码时,您可以在不缩小的情况下构建应用程序。这将保持变量名称完整并防止浏览器优化变量,因此您可以尝试在本地重新创建和调试。

© www.soinside.com 2019 - 2024. All rights reserved.