0

The code below throws an exception in firefox:

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

the exception is this:

Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]

Yet if I change code and use this.toString() as follows, it works:

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

If "this" is a string, why do I need to do toString()? Is there a nuance of javaScript which I am missing or am I just being a moron? Please tell me it's a nuance.

3 Answers 3

1

Distinction between string primitives and String objects JavaScript automatically converts primitives and String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

~From MDN Read More

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

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

For ex:

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

And the output of the div is Can't use String object. Demo here

Sign up to request clarification or add additional context in comments.

Comments

1

For some reason it do not work with array. Try this.

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

Comments

1

if you try this:

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

you'll see in the console that this and this.toString() aren't actually the same thing. It would seem that this is a String object and that this.toString() is an actual string.

Comments

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.