首页 > 解决方案 > 为什么我不能分配 const 但我可以控制台记录它?

问题描述

我做了一些java脚本练习,让几个链接按字母顺序排列。

这是HTML

  <a href="#"> a is good </a>
  <a href="#"> c is good </a>
  <a href="#"> b is good </a>

JAVASCRIPT:

const allhref= document.getElementsByTagName('a');
for (let index in allhref)
  console.log(allhref[index].innerHTML);
<a href="#"> a is good </a>
<a href="#"> c is good </a>
<a href="#"> b is good </a>

看起来没问题,但是当我尝试将 txt 分配给 const 时,出现了错误(未捕获的 SyntaxError:意外的令牌 const)。这是代码。

const allhref= document.getElementsByTagName('a');
for (let index in allhref)
  alltext = allhref[index].innerHTML;
console.log(alltext);
<a href="#"> a is good </a>
<a href="#"> c is good </a>
<a href="#"> b is good </a>


感谢您的回复。这有点奇怪,我确实在我的电脑上测试过它有错误。尝试不同的在线编辑器,没有错误。这是代码:

  <!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  </head>
  <body>
    <a href="#">a is good </a>
    <a href="#">c is good </a>
    <a href="#">b is good </a>
  <script type="text/javascript">        
    const allhref= document.getElementsByTagName('a');
    for (let index in allhref)
      const alltxt = allhref[index].innerHTML;
    console.log(alltxt);
    // console.log(allhref[index].innerHTML);
  </script>
  </body>
  </html>

标签: javascriptarrays

解决方案


const 在 JavaScript 中是不可变的。您不能为 const 分配新值。为了能够做到这一点,请将 const 更改为 let。


推荐阅读