如果使用位置替换,则运行两个条件的JavaScript if语句

如果使用位置替换,则运行两个条件的JavaScript if语句,javascript,Javascript,我有下面的if语句,它在documentready上查找散列(此代码在页面上不再运行)。若并没有散列,那个么使用replace添加一个散列,这样它就不会触发hashchange事件 if( window.location.hash == '' ) { console.log('no hash'); location.replace(location.href.replace(/\/?$/, '#/section-0/page-0')); // change the url w

我有下面的if语句,它在documentready上查找散列(此代码在页面上不再运行)。若并没有散列,那个么使用replace添加一个散列,这样它就不会触发hashchange事件

if( window.location.hash == '' ) {

    console.log('no hash');

    location.replace(location.href.replace(/\/?$/, '#/section-0/page-0')); // change the url without creating a hashchange

} else {

    console.log('has hash');

}

但是,如果我在没有散列的情况下访问页面,我将在控制台中看到
有散列
,并且替换将发生这怎么可能?因为控制台日志位于语句的另一部分。如果我注释掉replace,那么它只属于If语句的第一部分。它如何跳转到if语句中进行替换(但忽略第一个控制台日志),然后跳转到第二部分?

您所说的没有意义

我试图从您的代码中创建一个完整的示例:

<html>
<head>
<script type='text/javascript'>
    function x()
    {
        if( window.location.hash == '' )
        {
            console.log('no hash');
            location.replace(location.href.replace(/\/?$/, '#/section-0/page-0')); // change the url without creating a hashchange

            alert('changed!');
        }
        else
        {
            console.log('has hash');
        }
    }
</script>
</head>
<body>
    <button onclick="javascript:x()">test</button>
</body>
</html>
它表明:

  • 控制台
    无散列
  • 警觉的

  • @卡梅伦:需要更多的帮助吗?
    <html>
    <body>
        <script type='text/javascript'>
            if( window.location.hash == '' )
            {
                console.log('no hash');
                location.replace(location.href.replace(/\/?$/, '#/section-0/page-0')); // change the url without creating a hashchange
    
                alert('changed!');
            }
            else
            {
                console.log('has hash');
            }
        </script>
    </body>
    </html>