如果语句检查类型怎么样?

时间:2011-02-11 17:35:02

标签: javascript

我来自C#背景,需要更熟悉JS。我正在读一本书,在这个例子中:

var as = document.getElementsByTagName('a');
for(var i=0;i<as.length;i++){
    t=as[i].className;
    //Check if a link has a class and if the class is the right one
    if(t && t.toString().indexOf(popupClass) != -1)
    {
       //...
    }

if语句的一部分没有意义。什么是if(t)?我习惯if语句检查布尔值,但t是一个字符串,对吗?

6 个答案:

答案 0 :(得分:5)

if语句确实输入了强制。

if (o) block;

只会运行该块。如果o是“真实的”

以下值是假的:

"", null, undefined, false, 0, NaN

其余的都是真的。

可以找到一篇好文章here

更重要的是,你有很多死代码。

var as = document.getElementsByTagName('a');
for(var i=0;i<as.length;i++){
    t=as[i].className;
    // no need to check for whether t exists. No need to cast it to a string
    if(t.indexOf(popupClass) !== -1) // use !== for strict equality
    {
       //...
    }

答案 1 :(得分:2)

if(t)检查t是否真实

http://11heavens.com/falsy-and-truthy-in-javascript

在这种特定情况下,检查的最可能目的是消除t为nullundefined的可能性。

答案 2 :(得分:2)

JavaScript执行自动type conversion。这些值计算为布尔false

  • null
  • undefined
  • 0
  • ""
  • false
  • NaN

其他任何内容的评估结果为true

因此,它测试t是否具有某些 truthy 值,然后对t执行某些操作。如果未执行此操作(例如,如果tundefinednull),则t.toString()会抛出错误。

答案 3 :(得分:1)

查看“How good C# habits can encourage bad JavaScript habits”帖子。

基本上,所有这些值都是相同的(假):

false
null
undefined
"" // empty string
0
NaN // not a number

因此if(t)会检查对象是falsenullundefined等等......

答案 4 :(得分:0)

if(t)检查t是否是有效对象。 if(t)就像if(t!= null)。

答案 5 :(得分:0)

  

类型转换

     

JavaScript是一种弱类型的语言,因此它会尽可能地应用类型强制

// These are true
new Number(10) == 10; // Number.toString() is converted
                      // back to a number

10 == '10';           // Strings gets converted to Number
10 == '+10 ';         // More string madness
10 == '010';          // And more 
isNaN(null) == false; // null converts to 0
                      // which of course is not NaN

// These are false
10 == 010;
10 == '-10'
     

为避免建议使用strict equal operator

     

但这仍然无法解决JavaScript弱键入系统引起的所有问题。

来源:JavaScript Garden