0

I have the following class for which I wish to create a series of instances:

function rashnik(size, name) {
    var img = document.createElement('img');
    img.src = "pics/"+name+".jpg";
    img.height = size;
    img.width = size;
    img.id = name;
    d = 300-size;
    img.style.marginBottom = d/2;
    img.style.marginLeft = 50;
    var gal = document.getElementById("gallery");
    gal.appendChild(img);
};

Now, Iv'e created this function to create the instances:

function creater(names) {// the argument "names" would be a two-dimensional array 
    for (var a = 0; a < names.length; a++){
        var names[a][0] = new rashnik(names[a][1], names[a][0]); // right here is where I get the error
    }
}

And this is how I try to call it:

var friends = [["adi","300"],["tom","200"],["sleg","100"],["dorc","50"],["dork","25"]];
creater(friends);

The thing is, the var names[a][0] part throws me an error, which I totally understand; I want to create an object whose name is the same as the string stored in names[a][0], but, well, it just doesn't work that way. Does anyone have an idea as to what I could to to make it happen?

1 Answer 1

2

Cleaned up. I think this is doing what you want:

  • Create a new class instance in the loop, so it's an object
  • Put something in that object. I put the img in as an example.
  • Use the name as the "key" of a returning object. I access that in the alert in the code below by using resultsView['adi'] but could have also done resultsView.Adi

http://jsfiddle.net/w7wKW/

function rashnik(size, name)
{
var img=document.createElement('img');
img.src = "pics/"+name+".jpg";
img.height = size;
img.width = size;
img.id = name;
d = 300-size;
img.style.marginBottom = d/2;
img.style.marginLeft = 50;
var gal = document.getElementById("gallery");
gal.appendChild(img);

    this.img = img;
    return this;
};


function creater(names)
{//the argument "names" would be a two-dimensional array
    var results = { };
for(var a=0; a<names.length; a++)
{
results[names[a][0]] = new rashnik(names[a][1], names[a][0]);
}

    return results;
}

var friends = [["adi","300"],["tom","200"],["sleg","100"],["dorc","50"],["dork","25"]];
var resultsValue = creater(friends);

alert(resultsValue['adi'].img.src);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that did it. Could you explain why? Especially the result = {} part?
result = { }; creates an empty object. I could have done result = { hello: 'world' } after which I could have done result.hello or result['hello'] to access the string world. If this answers your question, please accept the answer, thanks!

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.