0

I need to pass an array as parameter but i have a problem, i dont know how to explain it so here is the example:

I have this code:

var doc = document;

    var Class = {};

    Class.Validate = function(opc)
    {
        alert(opc.id);//
return Class;// when returns the object the alert trigger as expected showing "#name"
    };

Class.Validate({
    id: "#name",
})

But what im trying to do is this:

var Class = {};
    Class.Validate = function(opc)
    {
        alert(opc.name);//when the object is return show display "carlosmaria"
return Class;//

    };

Class.Validar({
    name: {field:"carlos",field:"maria"},
})

how can i archived that?

2
  • 1
    Those are not arrays, but objects. And a single key can only be used once per object, {field:…,field:…} is invalid. Also, please fix your "method" name Validar/Validate. Commented Mar 2, 2013 at 16:56
  • I spelled that wrong, thx. Do you know how solve this? I really need this. Commented Mar 2, 2013 at 16:57

2 Answers 2

2

alert(opc.name) should return something like {Object object} because it's an objet. The second point is that your object has twice "field" as property.

If you want to use an array, you should call this way:

Class.Validar({
    name: ["carlos", "maria"]
})

Then, you could loop over opc.name to concatenate a full name. Something like this:

Class.Validate = function(opc)
{
    var name = "";
    for (var i=0, len=opc.name.length; i<len; ++i) {
        name += opc.name[i];
    }
    alert(name);//when the object is return show display "carlosmaria"
    return Class;//
};
Sign up to request clarification or add additional context in comments.

2 Comments

Your loop looks a bit complicated. Why dereference len, but not opc.name? And why not just use opc.name.join("")?
The join method is, of course, a good solution to just concatenate strings from an array. But It seems to me that the need here is more than just concatenate. So by looping the array items, you get more flexibility to do more things. Everything depends on what Einer needs to do.
1

Consider using actual arrays (via array literals):

Class.Validate({
     name: ["carlos", "maria"]
});

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.