是使用ES6的DOM HTMLCollection-阵列样元素的常数



我想了解使用const关键字(ES6)将htmlCollection视为constand,或者使用var键字将其视为变量。

是什么让我感到困惑,事实是,const按钮在前循环中发生了变化,但在类似阵列的对象上访问了蜂蜜。

(function IIFE() {
    'use strict';
    
    
    
    const buttons = document.getElementsByTagName('button');
    
    for (let i = 0, l = buttons.length; i < l; i += 1) {
        buttons[i].onclick = function () {
            
            for (let i = 0; i < l; i += 1) {
                buttons[i].className = '';
                this.className = 'active';
            }
            
        };
    }
    
    
    
    console.log(typeof(buttons)); // object
    console.log(buttons);         // HTMLCollection
    
    
}());
ul {
    list-style-type: none;
    width: 196px;
    padding: 10px 20px;
    margin-left: auto;
    margin-right: auto;
}
li {
    display: inline-block;
}
button {
    font-size: 34px;
    font-weight: 900;
    font-family: , "andale mono";
    border-radius: 4px;
    margin-right: 20px;
}
.active {
    background: rgba(51, 181, 229, 0.4);
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Test UI</title>
    <link href="style.css" rel="stylesheet">
</head>
<body>
    <ul>
        <li><button class="active">A</button></li>
        <li><button>B</button></li>
        <li><button>C</button></li>
    </ul>
                                 
<script src="script.js"></script>
</body>
</html>

是什么让我感到困惑是事实,const按钮是 在循环中更改,但在类似阵列的情况下访问了蜜蜂 对象。

const仅关键字可防止您更改变量的值(原始或参考)。您仍然可以修改变量的属性

所以你不能做以下

const buttons = document.getElementsByTagName('button');
buttons = document.getElementsByTagName('button');//this line will throw an error with or without const again

但是您可以做以下

const buttons = document.getElementsByTagName('button');
buttons[0].className = ''; //only property is being modified not the object reference value itself

最新更新