2010-03-26 16 views
14

Sono abbastanza confuso con il comportamento degli array di stringhe quando li eseguo tramite il metodo jQuery.each(). Apparentemente, le stringhe diventano oggetti jQuery all'interno della funzione di callback. Tuttavia, non posso usare il metodo this.get() per ottenere la stringa originale; facendo così si innesca un questo.get non è una funzione messaggio di errore. Suppongo che il motivo sia che non è un nodo DOM. Posso fare $(this).get() ma la mia stringa diventa una matrice (da "foo" a ["f", "o", "o"]).Le stringhe nella matrice non sono più stringhe dopo jQuery.each()

Come posso restituirlo alla stringa? Ho bisogno di ottenere una variabile di tipo String perché la passo ad altre funzioni che confrontano i valori tra di loro.

Allego un banco di prova autonomo (richiede la console di 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

Ho appena avuto lo stesso problema, tuttavia ho scoperto che funziona come previsto in modalità rigorosa. – Joost

risposta

13

modifica/chiarimento: le funzioni calllback accettano due argomenti, il secondo è il valore della variabile. Usalo invece di this Ho testato entrambe le varianti e tutto sembra funzionare come previsto (le stringhe sono ancora stringhe).

>>> $.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

Oh my ... Ora capisco! –

+2

'this' non è un oggetto jQuery quando esegue il looping di stringhe, avvolge la stringa in un oggetto' String'. Se fai 'this.toString()' otterrai una stringa regolare. – David

3

Questo funziona nel mio Firefox 3.5:

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

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

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

La console mostra

string 
string
+0

Hmmm ... Mi hai dato un'idea: 'String (this)' –

+0

@ Álvaro G. Vicario: Sembra buono :) Sono praticamente un noob JavaScript, quindi tendo ad usare il primo hack che funziona – balpha

Problemi correlati