布尔值在 JavaScript 函数中不会改变
我有以下代码:
const ships = (length) => {
isSunk = false
console.log('BEFORE: ' + isSunk)
const shipSize = length
let hits = []
const hitLocation = location => {
hits.push(location);
isSunk = true;
console.log('INSIDE: ' + isSunk)
}
console.log('AFTER: ' + isSunk)
return {
isSunk,
hitLocation,
hits,
shipSize
}
}
const two = ships(2)
two.hitLocation(1)
two.hitLocation(2)
console.log('FINAL: ' + two.isSunk)
console.log('HITS: ' + two.hits)
当我最后调用它时,是否有原因 isSunk
没有保存为 true
?
是因为嵌套函数的原因吗?
I have the following code:
const ships = (length) => {
isSunk = false
console.log('BEFORE: ' + isSunk)
const shipSize = length
let hits = []
const hitLocation = location => {
hits.push(location);
isSunk = true;
console.log('INSIDE: ' + isSunk)
}
console.log('AFTER: ' + isSunk)
return {
isSunk,
hitLocation,
hits,
shipSize
}
}
const two = ships(2)
two.hitLocation(1)
two.hitLocation(2)
console.log('FINAL: ' + two.isSunk)
console.log('HITS: ' + two.hits)
Is there a reason why isSunk
is not saved as true
when I call it in the end?
Is it due to the nested functions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您将布尔值设置到对象中时,它就是该值。它不是对变量的引用。因此,当您更改变量时,您在返回的对象中保存的值不会更新。
您可以使用函数来获取值
另一种选择是使用类。
When you set the boolean into the object, it is that value. It is not a reference to the variable. So when you change the variable, the value you saved inside of the object that you returned is not updated.
You can use a function to get the value
Other option is to use a class.
发生这种情况的原因是
isSunk
只是一个局部变量和一个值,而hits
也是一个局部变量,但是一个数组,因此只是一个引用而不是一个值。当您在调用
ship()
时返回对象时,这些值和引用将在对象中返回。现在,当您调用
hitLocation()
时,它使用局部变量hits
向数组添加一个条目,并且由于数组只是局部变量hits< 的引用/code> 和
two
对象中的hits
具有相同的引用,因此它们指向相同的内存位置,因此可以使用返回的对象看到更新。另一方面,
hitLocation()
也会修改局部变量isSunk
,但由于您不返回它,并且它不是存储在变量two< 中的对象的引用/code> 未更新。
在我看来,解决这个问题的最佳方法是在这里使用类而不是对象。这比始终返回和/或传递要对函数执行某些操作的对象要简洁和清晰得多。
The reason this happens is that
isSunk
is just a local variable and a value in contrast tohits
which is also a local variable but an array and thus just a reference not a value.As you return the object when calling
ship()
these values and the reference get returned in an object.Now when you call
hitLocation()
it uses the local variablehits
to add an entry to the array and as the array is just a reference the local variablehits
and thehits
in thetwo
object have the same reference so they point to the same memory location, thus the update can be seen using the returned object.On the other hand
hitLocation()
also modifies the local variableisSunk
but as you do not return that and it is not a reference the object stored in variabletwo
is not updated.The best way to fix this to my mind is using a class instead of a object here. This will be much more concise and clear than returning and/or passing the object you want to perform some action on to a function all the time.