简体   繁体   English

即使没有传递任何内容,JavaScript布尔变量也为true

[英]JavaScript boolean variable is true even if nothing is passed

I have the following if clause: 我有以下if子句:

if(trackingEnabled && tracking) {
  // do something
}

Both variables are function parameters. 两个变量都是函数参数。 In some cases the tracking variable is set as a boolean, in some cases not. 在某些情况下, tracking变量设置为布尔值,在某些情况下不是。

If I lookup the variable's type (in the case that I don't pass a value), then it is a simple Object. 如果我查找变量的类型(在我没有传递值的情况下),那么它是一个简单的对象。

My question is now, why is the tracking variable interpreted as a boolean (value is true) when I don't pass anything to the function? 我现在的问题是,当我没有向函数传递任何内容时,为什么跟踪变量被解释为布尔值(值为true)?

Can you paste the whole code (method call). 你可以粘贴整个代码(方法调用)。 I've tried code below in IE9, FF14 and Chrome 23, and code inside if statemenet never gets executed, while typeof b is evaluated to either undefined and object, respectively to method calls. 我在IE9,FF14和Chrome 23中尝试了下面的代码,如果statemenet永远不会被执行,则代码在里面,而typeof b分别被评估为undefined和object,方法调用。

function f(a,b){
 console.log("Type of b is " + typeof b);
 if(a && b){
     console.log(a);
     console.log(typeof a);
     console.log(b);
     console.log(typeof b);
 }
}
f(true);
f(true,null);

I see two possible causes 我看到两个可能的原因

1) You have something passed in function 1)你在功能上传递了一些东西

2) You have some weird Javascript execution environment 2)你有一些奇怪的Javascript执行环境

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM