14

I'm pretty confused with the behaviour of arrays of strings when I loop them through the jQuery.each() method. Apparently, the strings become jQuery objects inside the callback function. However, I cannot use the this.get() method to obtain the original string; doing so triggers a this.get is not a function error message. I suppose the reason is that it's not a DOM node. I can do $(this).get() but it makes my string become an array (from "foo" to ["f", "o", "o"]).

How can I cast it back to string? I need to get a variable of String type because I pass it to other functions that compare the values among them.

I enclose a self-contained test case (requires Firebug's console):

<!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
  • 1
    I just experienced the same issue, however found out that this works as expected in strict mode. Commented Jan 12, 2016 at 11:57

2 Answers 2

13

edit/clarification: calllback functions takes two arguments, the second one is value of the variable. Use it instead of this I have tested both variants and everything seems to work as expected (strings are still strings).

>>> $.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
Sign up to request clarification or add additional context in comments.

1 Comment

this is not a jQuery object when looping through strings, it wraps the string in a String object. If you do this.toString() you will get a regular string.
3

This works in my Firefox 3.5:

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

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

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

The console shows

string
string

2 Comments

Hmmm... You gave me an idea: String(this)
@Álvaro G. Vicario: Sounds good :) I'm pretty much a JavaScript noob, so I tend to use the first hack that works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.