Reputation: 130
Console log is giving me "undefined". I can't find a way to add object properties inside myBox object with "addBook" function. Maybe I'm just calling it wrong, but I think it should be correct way to do it.
function addBook (box, name, writer) {
box["# of Books"]++;
box["book" + box["# of Books"]] = {title: name, author: writer};
}
var myBox = {
height: 10,
width:50,
volume:400
};
addBook(myBox, "Javascript Ninja", "Ninja");
console.log(myBox.book1.title);
Upvotes: 0
Views: 38
Reputation: 382092
The problem is you try to increment an undefined value, thus you get NaN
.
Simply initialize your counter :
function addBook (box, name, writer) {
box["# of Books"]++;
box["book" + box["# of Books"]] = {title: name, author: writer};
}
var myBox = {
height: 10,
width:50,
volume:400
};
myBox["# of Books"]=0; // <-- there
addBook(myBox, "Javascript Ninja", "Ninja");
console.log(myBox.book1.title);
When you encounter such a problem, you should first debug it yourself, seeing the values step by step. Read Debugging JavaScript.
Upvotes: 1