在JavaScript中声明未赋值的let变量为何可行?事件委托示例疑问
关于JavaScript事件委托示例中未赋值let变量的疑问
我在一个事件委托示例中看到这样的逻辑:点击9单元格表格的任意单元格时,该单元格(event.target)会变为红色,上一次点击的单元格则恢复原色。但我疑惑的是,为什么可以声明未赋值的let变量selectedTd,并且在highlight函数中直接使用它?
解答
这是JavaScript的基础特性在起作用,拆解开讲:
未赋值的let变量默认是undefined
用let selectedTd;声明但不给值时,变量会自动被初始化为undefined。highlight函数里的if (selectedTd)是检查变量是否为**“真”值**——undefined属于“假”值,所以第一次点击单元格时,这个if块会直接跳过,根本不会执行里面的代码,自然不会报错。这个变量是用来“记录上一次选中项”的
selectedTd是在全局作用域声明的,只要页面不刷新,它的生命周期就和页面绑定。第一次点击单元格后,selectedTd = node会把当前点击的DOM元素存进去;后续再点击时,它已经存储了上一次的单元格元素,这时if (selectedTd)就会生效:先移除上一个单元格的高亮样式,再把新的单元格赋值给它并添加高亮。为什么不用初始值?
因为第一次点击时根本不存在“上一次选中的单元格”,直接跳过移除样式的逻辑就好,这样写代码更简洁,没必要额外给它设置初始值。
完整代码示例
JavaScript代码
let table = document.getElementById('bagua-table'); let selectedTd; table.onclick = function(event) { let target = event.target; while (target != this) { if (target.tagName == 'TD') { highlight(target); return; } target = target.parentNode; } } function highlight(node) { if (selectedTd) { // 初始为undefined,第一次判断会跳过 selectedTd.classList.remove('highlight'); } selectedTd = node; selectedTd.classList.add('highlight'); }
CSS代码
#bagua-table th { text-align: center; font-weight: bold; } #bagua-table td { width: 150px; white-space: nowrap; text-align: center; vertical-align: bottom; padding-top: 5px; padding-bottom: 12px; } #bagua-table .nw { background: #999; } #bagua-table .n { background: #03f; color: #fff; } #bagua-table .ne { background: #ff6; } #bagua-table .w { background: #ff0; } #bagua-table .c { background: #60c; color: #fff; } #bagua-table .e { background: #09f; color: #fff; } #bagua-table .sw { background: #963; color: #fff; } #bagua-table .s { background: #f60; color: #fff; } #bagua-table .se { background: #0c3; color: #fff; } #bagua-table .highlight { background: red; }
HTML代码
<table id="bagua-table"> <tr> <th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th> </tr> <tr> <td class="nw"><strong>Northwest</strong> <br>Metal <br>Silver <br>Elders </td> <td class="n"><strong>North</strong> <br>Water <br>Blue <br>Change </td> <td class="ne"><strong>Northeast</strong> <br>Earth <br>Yellow <br>Direction </td> </tr> <tr> <td class="w"><strong>West</strong> <br>Metal <br>Gold <br>Youth </td> <td class="c"><strong>Center</strong> <br>All <br>Purple <br>Harmony </td> <td class="e"><strong>East</strong> <br>Wood <br>Blue <br>Future </td> </tr> <tr> <td class="sw"><strong>Southwest</strong> <br>Earth <br>Brown <br>Tranquility </td> <td class="s"><strong>South</strong> <br>Fire <br>Orange <br>Fame </td> <td class="se"><strong>Southeast</strong> <br>Wood <br>Green <br>Romance </td> </tr> </table>
内容的提问来源于stack exchange,提问作者Herma
相关产品推荐
相关产品推荐

