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

JavaScript if statement running both conditions if location replace used

本文关键字:如果 条件 位置 替换 两个 语句 if 运行 JavaScript      更新时间:2023-09-26

我有下面的if语句,查找文档准备好的散列(这段代码永远不会在页面上再次运行)。如果没有散列,则使用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');
}

但是,如果我访问没有散列的页面,我将在控制台中看到的是has hash,并且替换将发生…这怎么可能?因为该控制台日志位于语句的不同部分。如果我注释掉替换,那么它只属于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>

打开default时,代码执行如下:

    <
  1. 点击按钮/gh>
  2. 控制台no hash
  3. <
  4. 警告/gh><
  5. 点击按钮/gh>
  6. Console has hash

如果你把没有函数声明的代码放在代码体中(这样它就会一直执行),像这样:

<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>
显示了

:

  1. Console no hash
  2. <
  3. 警告/gh>