0
var events = [
    {id: 100,url: "mc.jsp?id=" + id},
    {id: 200,url: "mc2.jsp?id=" + id},
    {id: 300,url: "mc2.jsp?id=" + id}
]

When run, the url equals mc.jsp?id=undefined, so how can assign the id (100) to the url to get the value of mc.jsp?id=100? And also make the second url as mc2.jsp=200 and third one mc2.jsp?id=300 so I cannot make assignment outside the array.

1
  • 3
    What you're trying to do won't work. Show us more of the loop and we'll be able to give better answers. Commented May 20, 2012 at 21:30

4 Answers 4

2

You can't access other properties in an object literal on constructions. You get an undefined because you have no variable id. You will need to use:

var id = 100;
var events = [{"id":id, "url":"mc.jsp?id=" + id}];

or:

var event = {id: 100};
event.url = "mc.jsp?id=" + event.id
var events = [event];

but you could define a getter:

var events = [{id: 100, get url() { return "mc.jsp?id="+this.id; } }];

which is very complicated and difficult to understand. Maybe it's better to do something like this:

function MyEvent(id, mc) {
    this.id = id;
    this.mc = mc;
}
MyEvent.prototype.getUrl = function() {
    return "mc"+this.mc+".jsp?id="+this.id;
};

var events = [new MyEvent(100, ""), new MyEvent(200, "2"), ...];

However, there should be no such problem. If you hardcode the numbers, why don't you hardcode the urls? If you don't want the redundancy, just don't store the id two times and append it each time you need it.

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

7 Comments

but it is array, i cannot assign it outside
that way, every item i need one fucntiuon inside the arrat?
Things start to complicated when prototype comes in...But it is convenience!
@Bergi - Hey look, found something interesting. The first one is mc.jsp and the others are mc2.jsp. You might want to change something?
@juggernaut: No, it's pure JavaScript... There are good and many tutorials about that on the web.
|
0
 var id = 100, events = [{id: id, url: "mc.jsp?id=" + id}];

Comments

0

You cannot add id because its a name of a property, not a variable. You can do:

var ids = [100,200,300];
var events = [];
for(var i = 0; i < ids.length;i++){
    events[i] = {id: ids[i],url: "mc.jsp?id=" + ids[i]};
}

2 Comments

but different item in array will have different value, so i cannot make all of them 100
You have already hard coded 100 in your code. Seems that you have another problem which you haven't mentioned in your question.
0

You can try something like it.

var event = {
 'id': 100,
 'url': 'mc.jsp?id=' + event.id
}

var events = [];
events.push(event);  

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.