0

I have a foreach loop (writen using MVC3's Razor engine) and I need to create a new object in the Popups array every iteration. Here's what I'm trying to run:

var popups = [];
var count = 0;

@foreach (var marker in Model) {
    <text>
    popups[count]["content"] = document.createElement("div");
    popups[count]["content"].class = "infobox-custom";
    popups[count]["content"].style.cssText = "padding: 5px; width: 600px;";
    popups[count]["content"].innerHTML = '<div class="professional"><h1>test</h1></div>';

    popups[count]["infobox"] = new InfoBox();

    popups[count]["marker"] = new MarkerInfo();
    count++;
    </text>
}
console.log(popups);

I'm getting the error:

Uncaught TypeError: Cannot set property 'content' of undefined

As you can see, I'm trying to encapsulate each individual marker's related information in a javascript object. I'm aiming to access everything I need by using something like popups[index].marker or popups[index].content.

I'm reading the book Javascript: The Good Parts and there is one part that mentions:

If the object does not already have that property name, the object is augmented:

What am I missing here?

2 Answers 2

2

Set popups[count] to an object before you start adding properties to it.

var popups = [];
var count = 0;

@foreach (var marker in Model) {
    <text>
    popups[count] = {};
    popups[count]["content"] = document.createElement("div");
    popups[count]["content"].class = "infobox-custom";
    popups[count]["content"].style.cssText = "padding: 5px; width: 600px;";
    popups[count]["content"].innerHTML = '<div class="professional"><h1>test</h1></div>';

    popups[count]["infobox"] = new InfoBox();

    popups[count]["marker"] = new MarkerInfo();
    count++;
    </text>
}
console.log(popups);
Sign up to request clarification or add additional context in comments.

Comments

1

You need to make popups an array of objects.

popups[count] = {}; // <<<<<<<<<<<<<<<<-----------------------------------
popups[count]["content"] = document.createElement("div");
popups[count]["content"].class = "infobox-custom";
popups[count]["content"].style.cssText = "padding: 5px; width: 600px;";
popups[count]["content"].innerHTML = '<div class="professional"><h1>test</h1></div>';

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.