JavaScript回调函数中的if语句执行异常问题排查求助
问题排查:if语句未正常修改变量的原因
我一眼就发现了问题的核心——你在messageToModal函数的两个if判断块里,错误地重复使用let声明了modal_message变量,导致最终插入到DOM的始终是初始值"NO NO NO"。
具体原因分析
JavaScript中,let声明的变量具有块级作用域。当你在if (isLocked === true)块内写let modal_message = ...时,相当于在这个块的局部作用域里创建了一个全新的modal_message变量,它和函数开头声明的那个modal_message完全是两个独立的变量。当这个if块执行完毕,局部的modal_message就会被销毁,函数外层的变量根本没有被修改。
而你用来测试的if ('foo' != 'bar')能正常执行,是因为它没有涉及变量作用域的冲突问题,只是单纯的条件判断。
修正方案
只需要去掉两个if块内的let关键字,直接给已经声明好的modal_message赋值即可:
function messageToModal(userHasLocked) { let isLocked = userHasLocked; console.log('in messageToModal'); console.log('other user has locked is: ' + userHasLocked); console.log('isLocked is: ' + isLocked); console.log(typeof userHasLocked); if ('foo' != 'bar') { console.log('Foo is NOT Bar!') } let modal_message = "NO NO NO"; if (isLocked === true) { // 移除let,直接赋值给外层变量 modal_message = "The other user has locked this evaluation."; } if (isLocked != true) { // 同样移除let modal_message = "The other user has not locked this evaluation."; } console.log('gotta push the message now: '+ modal_message); $("#lockControlMessage").text( modal_message ); }
额外优化建议
你还可以把两个if判断改成if...else结构,这样不仅逻辑更清晰,还能避免重复判断:
function messageToModal(userHasLocked) { let isLocked = userHasLocked; console.log('in messageToModal'); console.log('other user has locked is: ' + userHasLocked); console.log('isLocked is: ' + isLocked); console.log(typeof userHasLocked); if ('foo' != 'bar') { console.log('Foo is NOT Bar!') } let modal_message; if (isLocked === true) { modal_message = "The other user has locked this evaluation."; } else { modal_message = "The other user has not locked this evaluation."; } console.log('gotta push the message now: '+ modal_message); $("#lockControlMessage").text( modal_message ); }
另外,从你的调试日志里的typeof userHasLocked输出可以确认,传递过来的参数确实是布尔值,所以类型判断没有问题,核心问题就是变量作用域的冲突。
内容的提问来源于stack exchange,提问作者Hanny
相关产品推荐
相关产品推荐

