0

I am have a class in JS job ,now I want a simple way to create its object in a for loop, the way I trying to do this is:

 for(var i=1;i<=jobsCount;i++)
         {
          var eval("job"+i)=new job();

         }

But this syntax gives me an error as illegal life hand side assignment ,is there a simple way do this,?

2 Answers 2

4

If you want to dynamically create variables in the global context, you may do this :

window['job'+i]=new job();

But I'd suggest the use of an array to avoid cluttering the global context :

var jobs = [];
for(var i=1; i<jobsCount; i++){ // why starting at 1 ? shouldn't it be <= ?
      jobs[i] = new job();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Over here aren't we creating a array of objects?, I don't want an array I want individual object names like job1,job2,job3,job4 and so on....
What's the problem with the array? It's even better because you only need one variable. What you want to do is not a good idea but the window solution should work.
I have already written the code using this objects at first the number of object to be created were limited,so I manually created them like var job1=new job() and so on but now I require them to be dynamic ,if I create array I would have to modify and correct to much code
@Snedden27 The first solution ( window['job'+i]=new job();) builds individual variables job1, job2, etc.
0
var jobs = [];
for(var i=1;i<jobsCount;i++)
{
    jobs[i]=new job();

}

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.