简体   繁体   English

使用javascript限定符const时,Safari和Chrome的行为不同

[英]Different behavior between safari and chrome when using javascript qualifier `const`

i'm very new to javascript. 我对javascript很陌生。 i'm wondering why the code blow will give two different results between safari and chrome. 我想知道为什么代码打击会在safari和chrome之间给出两个不同的结果。

<!DOCTYPE html>
<html>
  <head>
    <h1> test </h1>
  </head>
  <body>
    <div id='test'> </div>
    <div id='num0' style='display:none'> number one</div>
    <div id='num1' style='display:none'> number two</div>

    <script type="text/javascript">
      for (var i = 0; i <2; i++){
        const data = document.getElementById("num"+i).innerHTML;
        var newDiv = document.createElement("div");
        newDiv.id = i;
        newDiv.innerHTML = data;
        document.getElementById('test').appendChild(newDiv);
      }
    </script>
  </body>
</html>

safari: 苹果浏览器:

test
number one
number two

chrome: 铬:

test
number one
number one

it seems safari ignored the const qualifier. Safari似乎忽略了const限定词。 is this a undefined behavior? 这是未定义的行为吗? what happened under the hood? 引擎盖下发生了什么?

Safari's behavior is right. Safari的行为是正确的。 const is block-scoped, so whenever the loop is repeated, the const -qualified variable of the previous iteration is no longer available, so the new const data declaration can succeed - just like let . const是块作用域的,因此每当重复循环时,先前迭代的const限定变量就不再可用,因此新的const data声明可以成功-就像let一样。 In strict mode, Chrome also behaves like Safari. 在严格模式下,Chrome的行为也类似于Safari。

In non-strict mode, Chrome uses a legacy form of const , where the (const) variable declaration is hoisted and attempts to update the variable are silently ignored. 在非严格模式下,Chrome使用传统形式的const ,其中会提升(const)变量声明,而对变量的更新尝试将被忽略。

Example: 例:

 function log(msg) { document.body.appendChild(document.createElement('div')).textContent = msg; } (function() { // Chrome 45 (BAD) : 0 0 0 log('No strict mode'); for (var i = 0; i < 2; ++i) { const data = i; log(data); } try { log(data); // Should fail } catch (e) { log(e); } })(); (function() { // Chrome 45 (GOOD): 0 1 ReferenceError: data is not defined 'use strict'; log('In strict mode'); for (var i = 0; i < 2; ++i) { const data = i; log(data); } try { log(data); // Should fail } catch (e) { log(e); } })(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM