1

Here is my condition: I have already known that I need fifteen objects to store event data, so I just declared fifteen variables:

var e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, 15;

function Event(title, content, logo, logo_in_black) {
    this.title = title;
    this.content = content;
    this.logo = logo;
    this.logo_in_black = logo_in_black;
}

According to the user click, I dynamically assign data to the object according to the user click:

e1 = new Event('Nike', 'BUY ONE GET ONE FOR FREE', logo_url, logo_url2);

Then show the result on the view:

$('#e-1').css('background-image', "url('" + e1.logo + "')");

I need to do the same thing fifteen times to put every event information to individual block looks like this: <div id="e-1">! So I just tried the following method and I thought it must be the solution: I put fifteen objects in an array.

var e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15;
var events = [e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15];

Assign the data and show on the view:

e1 = new Event('Nike', 'BUY ONE GET ONE FOR FREE', logo_url, logo_url2);
e2 = ...
e3 = ...

for (var i = 0; i < 15; i ++) {
    $('#e-' + (i + 1)).css('background-image', "url('" + events[i].logo + "')");
}

But the way I tried to access the attributes is wrong: events[i].logo Can anyone please tell me why this can't work? Thanks a lot!

1 Answer 1

3

You have to assign the variables before you put them into the array. The array assignment uses the currentvalues of the variables, it doesn't make the array refer implicitly to the variables.

But there's no need for the variables in the first place, just assign directly to the array:

var events = [
    new Event('Nike', 'BUY ONE GET ONE FOR FREE', logo_url, logo_url2),
    ...
];

Any time you find yourself naming variables with numeric suffixes, you should almost always be using an array instead.

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

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.