javascript 如何否定 JS 中的 bool 内部函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20588994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to negate bool inside function in JS?
提问by Miko?aj Biel
I'm writing some script now and I have a problem when trying to negate boolean inside a function. I mean this:
我现在正在编写一些脚本,但在尝试否定函数内的布尔值时遇到了问题。我的意思是:
var test = true;
function changeThisBoolPlease(asd){
asd=!asd;
}
alert(test);
changeThisBoolPlease(test);
alert(test);
alerts true, then true.
警报为真,然后为真。
Any ideas? Isn't JS reference perfect?
有任何想法吗?JS 引用不是很完美吗?
EDIT:
编辑:
Ok, this was only a part of my function:
好的,这只是我功能的一部分:
function przesun(kolor, figury, castlings, x1, y1, x2, y2, strona) {
kolor = nowaPozycjaKolor(kolor,x1, y1, x2, y2);
figury = nowaPozycjaFigur(figury,x1, y1, x2, y2);
strona = !strona;
}
Actually I cannot return this value. How to?
实际上我不能返回这个值。如何?
采纳答案by Adassko
Objects are not passed by reference but by value which is a reference (copy of reference)...
对象不是通过引用传递,而是通过作为引用(引用的副本)的值传递...
In your example you're not even passing an object but a primitive value type.
在您的示例中,您甚至没有传递对象,而是传递原始值类型。
If you want a reference, then you need to wrap it in object element like:
如果需要引用,则需要将其包装在对象元素中,例如:
var test = { val: true };
function changeThisBoolPlease(asd){
asd.val=!asd.val;
}
alert(test.val);
changeThisBoolPlease(test);
alert(test.val);
回答by robbmj
You are just changing the value of asd
in the example in your question.
您只是asd
在您的问题中更改示例中的值。
try this
试试这个
var test = true;
function changeThisBoolPlease(asd){
return !asd;
}
alert(test);
test = changeThisBoolPlease(test);
alert(test);
Alternatively but not recommended, you could do it this way
或者但不推荐,你可以这样做
var test = true;
function changeTestBoolPlease(){
test = !test;
}
alert(test);
changeTestBoolPlease();
alert(test);
回答by crad
It's a scoping issue. Just return and set:
这是一个范围界定问题。只需返回并设置:
var test = true;
function changeThisBoolPlease(asd){
return !asd;
}
alert(test);
test = changeThisBoolPlease(test);
alert(test);