将布尔值作为函数参数传入后无法修改,如何解决?
修复布尔值无法修改的问题
你代码里的问题在于JavaScript基本类型是按值传递的。当你把width传给函数参数boolean时,函数拿到的只是width的一个副本,修改这个副本根本不会影响外面的原变量width。
下面是几种可行的修复方案:
方案1:直接在函数中操作目标变量(简单直接)
如果这个函数只负责修改width,可以直接在函数里操作width变量,不用传参数:
let width = false let height = false function updateWidth() { const inputVal = document.getElementById("input").value width = inputVal !== "" console.log(width) console.log(height) } document.getElementById("input").addEventListener('keyup', updateWidth)
方案2:用对象包裹布尔值(支持灵活修改不同变量)
如果需要同一个函数修改width或height,可以把布尔值放在对象里——对象是引用传递,修改对象的属性会同步到原对象:
const dimensions = { width: false, height: false } function updateBoolean(targetKey) { const inputVal = document.getElementById("input").value dimensions[targetKey] = inputVal !== "" console.log(dimensions.width) console.log(dimensions.height) } document.getElementById("input").addEventListener('keyup', function(){ updateBoolean('width') }) // 要修改height时,调用updateBoolean('height')即可
方案3:让函数返回新值,外部赋值
函数根据输入值返回对应的布尔状态,调用时把返回值赋值给目标变量:
let width = false let height = false function getBooleanState() { const inputVal = document.getElementById("input").value return inputVal !== "" } document.getElementById("input").addEventListener('keyup', function(){ width = getBooleanState() console.log(width) console.log(height) })
内容的提问来源于stack exchange,提问作者Marcel
相关产品推荐
相关产品推荐

