Solution: Objects
Review possible solutions to the tasks for the objects challenge.
We'll cover the following...
Solution 1
Here is a possible solution for adding and removing items from a list object.
Press + to interact
const myList = {items: [],add(item) {this.items.push(item)},remove(item) {let index = this.items.indexOf(item)if (index !== -1) {this.items.splice(index, 1);}}}// Adding to the listmyList.add('Apples');console.log("Adding Apples to the list: ", myList.items)myList.add('Bananas');myList.add('Oranges');console.log("Final contents of the list: ", myList.items);myList.remove('Bananas');console.log("After removing Bananas the list is: ", myList.items);
Explanation
-
Lines 1–2: The
myList
object is created with an empty items array. -
Lines 3–5: The function
add()
...