同类型变量为何不相等?为何需将dropdowns[i]赋值给openDropdown?
dropdowns[i] to openDropdown? Great question! Let's unpack why this seemingly redundant assignment is actually a smart coding practice:
Boosts Readability & Semantic Clarity
The variable nameopenDropdownimmediately signals what this element represents — the dropdown that might be in an open state. Compare that todropdowns[i], which only tells you it's an item from a collection, forcing readers to infer its purpose. Clear, intent-driven variable names make code easier to understand at a glance and debug later.Avoids Repeated Dynamic DOM Queries
document.getElementsByClassName()returns a dynamic HTMLCollection, meaning it updates automatically if the DOM changes behind the scenes. Every time you referencedropdowns[i], the browser may re-scan the DOM to fetch the current element at that index. By assigning it toopenDropdown, you cache the element once and reuse the reference, which is more efficient (especially if you later add more operations to this element).Improves Maintainability
If you ever need to expand the logic for this dropdown — like modifying its style, adding accessibility attributes, or attaching event listeners — having it stored in a named variable means you only write the reference once. No more copyingdropdowns[i]multiple times, which cuts down on typos and makes code updates cleaner.
For example, if you later wanted to add:
openDropdown.setAttribute('aria-expanded', 'false');
Using the variable makes this change straightforward, instead of repeating dropdowns[i] again.
Even though dropdowns[i] and openDropdown reference the same element right now, the assignment adds clarity, efficiency, and flexibility to the code that pays off long-term.
内容的提问来源于stack exchange,提问作者Mostafa Khan

