2012-01-26 32 views
0

的集合下面的代码抛出在Firefox异常:jQuery的每个字符串

$(function(){ 
     $(["one","two","three"]).each(function(){ 
      if(this == "one") 
       $("div#msg").html(this); 
     }); 
    }); 

例外是这样的:

无法转换的JavaScript参数arg 0 [nsIDOMDocumentFragment.appendChild]

然而,如果我更改代码并使用this.toString()如下,它的工作原理:

$(function(){ 
    $(["one","two","three"]).each(function(){ 
     if(this == "one") 
      $("div#msg").html(this.toString()); 
    }); 
}); 

如果“this”是一个字符串,为什么我需要做toString()?有没有我缺少的javaScript的细微差别,或者我只是一个白痴?请告诉我这是一个细微差别。

回答

1

字符串基元和字符串对象之间的区别 JavaScript自动转换基元和字符串对象,以便可以为基元字符串使用字符串对象方法。在要在基元字符串上调用方法或发生属性查找的上下文中,JavaScript将自动包装字符串基元并调用方法或执行属性查找。

〜从MDN Read More

$("div#msg").html("one"); //works 

$("div#msg").html(new String("one")); // doesnt work 

对于前:

try {   
    $("div#msg").html(new String("one")); 
} catch (e) { 
    $("div#msg").html("Can't use String object"); 
} 

而div的输出为Can't use String objectDemo这里

+0

很好的解释 - 我很欣赏它。 –

1

出于某种原因,它不适用于数组。尝试这个。

$(["one","two","three"]).each(function(i, val){ 
     if(val == "one") 
      $("div#msg").html(val); 
}); 
1

,如果你试试这个:

$(function(){ 
     $(["one","two","three"]).each(function(){ 
      console.log(this); 
      console.log(this.toString()); 
     }); 
    }); 

你会在控制台thisthis.toString()实际上不是一回事看到。看起来this是一个String对象,而this.toString()是一个实际的字符串。

相关问题