缩小时出现JavaScript错误 [英] Javascript error when minified

查看:83
本文介绍了缩小时出现JavaScript错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jsMin.php https://github.com/rgrove/jsmin-php/

I'm minifying Javascript in production with jsMin.php https://github.com/rgrove/jsmin-php/

这是未缩小的JS代码:

Here is the unminified JS code:

  function arc(r, p, a) {
    return "A" + r + "," + r + " 0 " + +(a > Math.PI) + ",1 " + p;
  }

和最小化的代码:

function arc(r,p,a){return"A"+r+","+r+" 0 "++(a>Math.PI)+",1 "+p;}

缩小后,代码将引发意外标识符"错误.如果我在(a > Math.PI)之前拿了+符号,就可以了.

When minified, the code throws an 'unexpected identifier' error. If I take the + sign before (a > Math.PI) away, it works okay.

我猜我的问题分为两部分-当全部都在一行上时为什么会出错?我是否通过删除第二个+号来更改其工作方式?没有它似乎可以正常工作,但是我没有编写代码,所以我不确定它在做什么.

I guess my question has two parts - why is this an error when it's all on one line, and am I changing the way it works by removing the second + sign? It seems to work okay without it, but I didn't write the code so I'm not entirely sure what it's doing.

推荐答案

您不应从所提供的压缩代码中收到意外标识符"错误.如果您是的话,那是您使用它的JavaScript引擎中的一个错误.对于您最初发布的代码,确实如此:

You shouldn't be getting an "unexpected identifier" error from the minified code you've presented. If you are, it's a bug in the JavaScript engine you're using it with. That was true of the code you posted originally, which was:

function arc(r,p,a){return"A"+r+","+r+" 0 "+ +(a>Math.PI)+",1 "+p;}
// You used to have a space here -----------^

但是您已经发布了更新的代码:

But with the updated code you've posted:

function arc(r,p,a){return"A"+r+","+r+" 0 "++(a>Math.PI)+",1 "+p;}
// No space here anymore -------------------^

...这是一个问题,因为++是增量运算符(前缀[++a]或后缀[a++]).并且 that 需要一个标识符(要递增的东西). ++只是在该位置无效(您得到的确切错误可能会因JavaScript引擎而异).

...it's a problem, because the ++ is an increment operator (either the prefix [++a] or postfix [a++]). And that would need an identifier (the thing to increment). The ++ just isn't valid in that position (the exact error you get is likely to vary by JavaScript engine).

您可以通过轻微地更改代码来保护代码免受破坏者的侵害:

You can defend the code against the minifier doing this by changing it slightly:

function arc(r, p, a) {
  return "A" + r + "," + r + " 0 " + (+(a > Math.PI)) + ",1 " + p;
}

parren防止+和另一个+合并为++.他们还使意图更加清晰,恕我直言.

The parens prevent the + and the other + from getting combined into ++. They also make the intent a bit clearer, IMHO.

关于问题的第二部分,不,您不能删除该+,它将改变函数的工作方式.特别是,a > Math.PI将是truefalse,并且+在将其连接到小数位数之前在其上进行编号(对于true1,对于false0).细绳.如果删除它,则会在字符串中看到truefalse而不是10.

Re the second part of your question, no, you can't remove that +, it will change how the function works. In particular, a > Math.PI will be true or false, and the + is there to make it a number (1 for true, 0 for false) before it's concatenated to the string. If you remove it, you'll see true or false in the string instead of 1 or 0.

这篇关于缩小时出现JavaScript错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆