I am looking to learn how to add an object to array with multiple existing objects following the constructor function which I created.
//constructor function
function Bookdes(title, author, pages, current_page, available){
this.title = title;
this.author = author;
this.pages = pages;
this.current_page = current_page;
this.available = available;
}
//array of books
var bookarrays = [
new Bookdes("Fast Cars", "John Burns", 205, 43, "true"),
new Bookdes("Slow Cars", "Joe Fast", 70, 32, "false" ),
new Bookdes("Big Cars", "Darla Jean", 234, 42, "true"),
new Bookdes("Small Cars", "Dema Jones", 214, 34, "false"),
new Bookdes("Cars", "Alex Best", 235, 41, "true")
];
//Add two more books
bookarrays.push("Gasoline Car", "Johnny Walker", 200, 31, "true");
bookarrays.push("Natural gas car", "James Dean", 150, 21, "true");
console.log(bookarrays);
thanks,
asked Mar 16, 2015 at 0:06
Bigboy6
1092 gold badges3 silver badges13 bronze badges
1 Answer 1
The problem is that you don't call the constructor. The right call is:
bookarrays.push(new Bookdes("Gasoline Car", "Johnny Walker", 200, 31, "true"));
answered Mar 16, 2015 at 0:08
JuniorCompressor
20.1k4 gold badges33 silver badges58 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Bigboy6
Oh so close, but no cigar! Thank you for the help!
Bigboy6
How would I edit an existing element --- //Change book to available or not available Bookdes.prototype.checkout = function(avail){ if(avail === "true") Bookdes.prototype.available = "true"; else if(avail === "false") Bookdes.prototype.available = "false"; else console.error("Entry not accepted please enter true or false"); }; console.log(bookarrays[2].checkout("true")); console.log(bookarrays);
Explore related questions
See similar questions with these tags.
lang-js
"true"as a string, you should probably usetrue(the Boolean value).bookarrays.push( new Bookdes("Nice Cars", "Joe Mama", 72, 12, "false" ))