gpt4 book ai didi

javascript - 我们如何将 DOM 元素声明为 const 并仍然对其进行修改?

转载 作者:行者123 更新时间:2023-12-01 01:58:05 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Keyword 'const' does not make the value immutable. What does it mean?

(5 个回答)


4年前关闭。




我不明白为什么即使我们将 DOM 元素声明为常量,我们也可以更改它。如果我们不更改它,那么我们到底在做什么?
先感谢您。

const button = document.getElementsByTagName('button')[0];
const domElement = document.getElementsByTagName('div')[0];
button.addEventListener('click', e => {domElement.innerText = "how can I be modified even I am const?"});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>DOM Example</title>

</head>
<body>
<div>change me</div>
<button>Change a DOM element </button>
</body>
</html>

最佳答案

const只会阻止您更改变量引用指向的对象。它不会阻止您修改对象本身。

这将是非法的:

const x = 5;
x = 4; // ERROR

const x = { a: 1 };
x = { b: 2 }; // ERROR

但这很好:
const x = { a: 1 };
x.a = 5;

关于javascript - 我们如何将 DOM 元素声明为 const 并仍然对其进行修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48291307/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com