0

I have a constructor property that expects an array of type (just for example) Dog. Rather than creating an array, filling it with Dogs and then passing that to the property I would like to create that array dynamically in a for-loop.

So instead of

(...) new ConstructorFoo({
    property: [
        new Dog("1"),
        new Dog("2")
    ]
});  

I would like to use something like this:

(...) new ConstructorFoo({
    property: function() {
        var d = [];
        for(var i = 0; i < 10; i++) {
            d.push(new Dog(i));
        }
        return d;
    }
});

But as far as I understand this throws an exception because of type mismatch. property expects an array of dogs but gets a function (correct?).

I hope my question makes sense.

1
  • 1
    "correct?" - property doesn't expect anything, it's an attribute in an object, being passed to ConstructorFoo. ConstructorFoo expects its argument to be of a certain form, and we can't tell you exactly what unless you show ConstructorFoo. If you just want to create an array before passing it to ConstructorFoo, then georg's answer should serve you well. If something is being used to defineProperty, then you will need to show us what you are doing. Commented Aug 4, 2015 at 7:15

1 Answer 1

4

Just call it in place:

(...) new ConstructorFoo({
    property: (function() {
        var d = [];
        for(var i = 0; i < 10; i++) {
            d.push(new Dog(i));
        }
        return d;
    })()
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That's exactly what I was looking for but failed to find the correct words to do a decent search.

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.