2010-03-26 32 views
14

之後,數組中的字符串不再是字符串當我通過jQuery.each()方法循環它們時,我非常困惑與字符串數組的行爲。顯然,這些字符串成爲回調函數中的jQuery對象。但是,我不能使用this.get()方法獲取原始字符串;這樣做會觸發this.get不是函數錯誤消息。我想這是因爲它不是一個DOM節點。我可以做$(this).get(),但它使我的字符串成爲一個數組(從"foo"["f", "o", "o"])。在jQuery.each()

我該如何將它轉換回字符串?我需要得到一個String類型的變量,因爲我將它傳遞給其他函數,比較它們之間的值。

我附上一個自包含的測試案例(需要Firebug的控制檯):

<!DOCTYPE html> 
<html> 
<head><title></title> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<script type="text/javascript"><!-- 
$(function(){ 
    var foo = []; 
    var $foo = $(foo); 

    foo.push("987"); 
    $foo.push("987"); 

    foo.push("654"); 
    $foo.push("654"); 

    $.each(foo, function(i){ 
     console.log("foo[%d]: object=%o; value=%s; string=%o", i, this, this, $(this).get()); // this.get() does not exist 
    }); 
    $foo.each(function(i){ 
     console.log("$foo[%d]: object=%o; value=%s; string=%o", i, this, this, $(this).get()); // this.get() does not exist 
    }); 
}); 
//--></script> 
</head> 
<body> 

</body> 
</html> 
+1

我剛剛經歷過同樣的問題,但是發現這在嚴格模式下按預期工作。 – Joost 2016-01-12 11:57:42

回答

13

編輯/澄清:calllback函數有兩個參數,第二個是變量的值。使用它而不是this 我已經測試了兩種變體,並且一切似乎按預期工作(字符串仍然是字符串)。

>>> $.each(['foo','bar'], function(i, s){ console.info(s, typeof s) }) 
foo string 
bar string 

>>> $(['foo','bar']).each(function(i, s){ console.info(s, typeof s) }) 
foo string 
bar string 
+0

哦,我的... 現在我懂了! – 2010-03-26 11:41:47

+2

'this'在循環字符串時不是jQuery對象,它將字符串包裝在'String'對象中。如果你做'this.toString()',你會得到一個正常的字符串。 – David 2012-11-23 13:47:09

3

這工作在我的Firefox 3.5:

$(function(){ 
    var foo = []; 

    foo.push("abc"); 
    foo.push("def"); 

    $.each(foo, function(i){ 
     console.log(typeof ("" + this)); 
     }); 
}); 

控制檯顯示

string 
string
+0

嗯......你給了我一個主意:'String(this)' – 2010-03-26 11:36:27

+0

@ÁlvaroG. Vicario:聽起來不錯:)我幾乎是一個JavaScript noob,所以我傾向於使用第一個破解工作 – balpha 2010-03-26 12:10:27