Chrome V8 Bug?功能在第二次调用后表现不同 [英] Chrome V8 Bug? Function Acting different after being called a 2nd time

查看:95
本文介绍了Chrome V8 Bug?功能在第二次调用后表现不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看看下面的JavaScript。我已经拿出了一些东西,所以你可能会专注于问题的本质。



你会注意到我连续两次调用prepPath函数,传递完全相同的字符串。在firefox和IE8中,这个函数每次都会报警(如预期的那样)。但是,在Chromium 5.0.375.127(55887)Ubuntu 10.04中,函数第一次返回true,第二次调用返回false,尽管输入保持完全相同!

 < script type =text / javascript> 
函数prepPath(str)
{
var regX = /[^\s/\"'\\].*[^\s/\"'\\] /G;
if(regX.test(str))
{
alert(true:+ str);
}
else
{
alert(false;+ str);
}
}

prepPath(/ desktop); // alert:true
prepPath(/ desktop); //警报:false
< / script>

为什么在Chromium中第二次返回false?

解决方案

在规范中有些含糊不清的字面正则表达式应该被重置(回想它们有状态)。你可以这样做:

  var regX = new RegExp(/ [^ \ s /'\ \] * [^ \s /'\\] /克); 

现场示例: http://jsbin.com/irate



或者这个:

  var regX = /[^\s/\"'\\].*[^\s/\"'\\]/g; 
regX.lastIndex = 0;

现场示例: http://jsbin.com/irate/2



我收到了很多人的消息,我认为这实际上并不是一个彻头彻尾的错误,而是一个含糊不清的问题。这不仅仅是Chrome浏览器,其他一些浏览器版本也有类似的问题。


Please take a look at the following JavaScript. I've taken stuff out of it, so you may focus on the essence of the problem.

You'll notice that I call the prepPath function twice in a row, passing in the exact same string. In firefox and IE8, this function alerts true each time (as expected). But, in Chromium 5.0.375.127 (55887) Ubuntu 10.04, the function returns true the first time, and false the 2nd call, despite the input remaining exactly the same!

<script type="text/javascript"> 
    function prepPath(str)
    {   
        var regX = /[^\s/"'\\].*[^\s/"'\\]/g;
        if(regX.test(str))
        {
            alert("true: " + str);
        }
        else
        {
            alert("false; " + str);
        }
    }

    prepPath("/desktop"); // alerts: true
    prepPath("/desktop"); // alerts: false 
</script> 

Why is it returning false the second time in Chromium?

解决方案

There's some ambiguity in the spec about when literal regexes should get reset (recall that they have state). You can work around this by doing this:

var regX = new RegExp(/[^\s/"'\\].*[^\s/"'\\]/g);

live example: http://jsbin.com/irate

or this:

var regX = /[^\s/"'\\].*[^\s/"'\\]/g;
regX.lastIndex = 0;

live example: http://jsbin.com/irate/2

I'm informed by those who've looked into it more than I have that it's not actually an outright bug, but an ambiguity. And it's not just Chrome, some versions of other browsers have also had a similar problem.

这篇关于Chrome V8 Bug?功能在第二次调用后表现不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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