Javascript 什么是;如果(!';';。替换(/^/,字符串))”;做
在浏览缩小的Javascript代码时,我经常看到以下语句:Javascript 什么是;如果(!';';。替换(/^/,字符串))”;做,javascript,regex,Javascript,Regex,在浏览缩小的Javascript代码时,我经常看到以下语句: if (!''.replace(/^/, String)) { // ... } 这有什么用?似乎任何符合ECMA的JS解释器都会将字符串的开头替换为string(“”),这仍然会导致一个空字符串,其否定为true 在什么情况下,行为会有所不同?这可用于检查字符串函数是否未被粗心的开发人员覆盖 在JavaScript中,没有任何东西是不可变的,因此: !''.replace(/^/, String) true //conso
if (!''.replace(/^/, String)) {
// ...
}
这有什么用?似乎任何符合ECMA的JS解释器都会将字符串的开头替换为string(“”)
,这仍然会导致一个空字符串,其否定为true
在什么情况下,行为会有所不同?这可用于检查
字符串
函数是否未被粗心的开发人员覆盖
在JavaScript中,没有任何东西是不可变的,因此:
!''.replace(/^/, String)
true //console prints
String
function String() { [native code] } //console prints
String()
"" //console prints
String = "eDSF"
"eDSF" //console prints
String()
TypeError: string is not a function //console prints
!''.replace(/^/, String)
false //console prints
当然,这不是大多数人使用它的目的。
Github显示了具有相同用途的示例
// code-snippet inserted into the unpacker to speed up decoding
var _decode = function() {
// does the browser support String.replace where the
// replacement value is a function?
if (!''.replace(/^/, String)) {
// decode all the values we need
while ($count--) $decode[$encode($count)] = $keywords[$count] || $encode($count);
//...code code
}
};
这似乎是来自包装商,比如 那么,让我们下载代码,看看它说什么
// code-snippet inserted into the unpacker to speed up decoding
const JSFUNCTION_decodeBody =
//_decode = function() {
// does the browser support String.replace where the
// replacement value is a function?
' if (!\'\'.replace(/^/, String)) {
// decode all the values we need
while ($count--) {
$decode[$encode($count)] = $keywords[$count] || $encode($count);
}
// global replacement function
$keywords = [function ($encoded) {return $decode[$encoded]}];
// generic match
$encode = function () {return \'\\\\w+\'};
// reset the loop counter - we are now doing a global replace
$count = 1;
}
';
它似乎在检查当前浏览器是否支持回调作为replace()
的第二个参数,如果是,则利用回调加快速度
作为余数,javascript中的
String
是一个函数,在执行var foo=String('bar')时使用该函数代码>,尽管您可能很少使用该语法。出于好奇,您在哪里看到它?五个搜索结果:当您选中“Base62 encode”时,该代码出现在JS压缩器中。尝试打包警报(“示例”)
并查看输出。@RoryO'Kane堆栈溢出支持开箱即用的符号,只需引用它:这可能非常古老,因为它从explorer 7和explorer 5的怪癖开始就受到支持mode@raam86根据源代码,Dean Edwards packer可追溯到2004年之前(这可能意味着比实际情况更早)。有许多值可以指定给String
,这将使表达式作为一个整体仍然计算为true
,因此很遗憾,这不是它。如果您这样解释它,替换1和true将给出相同的行为和函数(){console.log(“DSF”)}
;它只检查String
是否仍然是一个函数,并且该函数在作为参数传递空字符串时仍然返回空字符串。没有那么有用,因为很多合法函数都可以这样做,而与原始字符串没有任何关系。