2

I want to create a "library" with multiple "shelves", but I can't figure out how to name each shelf differently while creating them using a for loop:

function library(initLibraryName, initNumberOfShelves, initNumberOfBooks)
{
    this.name = initLibraryName;
    this.numberOfShelves = initNumberOfShelves;
    this.numberOfBooks = initNumberOfBooks;
    for (var i = 0; i < numberOfShelves; i++)
    {
       this.shelf = new shelf(i, numberOfBooks/numberOfShelves);
    }
} 
7
  • 1
    You're re-assigning this.shelf every iteration. Put them in an array. Commented Jan 18, 2014 at 21:35
  • Just use an associative array Commented Jan 18, 2014 at 21:37
  • 1
    @EdHeal, no such thing in JS. Commented Jan 18, 2014 at 21:57
  • @Andy - Yes there is - See quirksmode.org/js/associative.html Commented Jan 18, 2014 at 22:02
  • 1
    That's an object. While it's helpful for programmers from other languages where there are such things to make the comparison, there's still no such thing as an associative array in JS. Commented Jan 18, 2014 at 22:09

2 Answers 2

2

I'm not sure why you creating new instances of shelf, but at first you should declare it

// by convention constructor name should start with uppercase letter
function Library(initLibraryName, initNumberOfShelves, initNumberOfBooks) {
    this.name = initLibraryName;
    this.numberOfShelves = initNumberOfShelves;
    this.numberOfBooks = initNumberOfBooks;
    this.shelf = []; // at first you need to define an array
    for (var i = 0; i < numberOfShelves; i++) {
        // then push Shelf instances to an array
        this.shelf.push(new Shelf(i, this.numberOfBooks / this.numberOfShelves)); 
    }
}

function Shelf(arg1, arg2) {
    this.prop1 = arg1;
    this.prop2 = arg2;
    this.method = function () {
        // some logic
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Thanks to: https://stackoverflow.com/users/3052866/user3052866

I realize now that I needed to have an array of shelves in my library class, and that you can't just create multiple objects as part of a function in JS!

Thanks to elclanrs for pointing out the latter!

1 Comment

This was my first post on stackoverflow, great to be a part of the community!

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.