javascript - 为什么我不能分配 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>
解决方案
const 在 JavaScript 中是不可变的。您不能为 const 分配新值。为了能够做到这一点,请将 const 更改为 let。
推荐阅读
- variables - 将工作表设置为从组合框获得的文本
- javascript - 当其中一个对象为空时,如何映射对象数组?
- jetbrains-ide - JetBrains Rider 在评估时崩溃
- firebase - Flutter 从 Firebase 存储中获取图像并在应用程序中显示
- cocoa - 在菜单栏下定位窗口?
- node.js - 在 Heroku 上使用 puppeteer 绕过 Cloudflare 的验证码
- javascript - 如何在不调整浏览器大小的情况下创建“滑入”动画?
- c# - WPF DataGrid Checkbox 不更新源
- javascript - 向多个幻灯片添加 Swipeleft 和 swiperight 功能
- r - 如何删除未在 R 中注册为空格的额外空格