4-4-objects.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. var attrs, coffee, coffees, to_print;
  2. coffee = {
  3. name: 'French',
  4. strength: 1
  5. };
  6. console.log(coffee);
  7. // Spaced-out writing
  8. coffee = {
  9. name: 'French',
  10. strength: 1
  11. };
  12. console.log(coffee);
  13. coffee = {
  14. name: 'French',
  15. strength: 1,
  16. brew: function() {
  17. return console.log(`Brewing ${this.name}`);
  18. },
  19. pour: function(amount = 1) {
  20. if (amount === 1) {
  21. return "Poured a single cup";
  22. } else {
  23. return `Poured ${amount} cups`;
  24. }
  25. }
  26. };
  27. coffee.brew();
  28. console.log(coffee.pour());
  29. console.log(coffee.pour(2));
  30. coffees = {
  31. french: {
  32. strength: 1,
  33. in_stock: 20
  34. },
  35. italian: {
  36. strength: 2,
  37. in_stock: 12
  38. },
  39. decaf: {
  40. strength: 0,
  41. in_stock: 0
  42. }
  43. };
  44. console.log(coffees);
  45. for (coffee in coffees) {
  46. attrs = coffees[coffee];
  47. // For key, value of object. Notice how the "for" applies to everything to its
  48. // left, including the console.log.
  49. console.log(`${coffee} has ${attrs.in_stock}`);
  50. }
  51. // It compiles exactly like this:
  52. for (coffee in coffees) {
  53. attrs = coffees[coffee];
  54. console.log(`${coffee} has ${attrs.in_stock}`);
  55. }
  56. to_print = (function() {
  57. var results;
  58. results = [];
  59. for (coffee in coffees) {
  60. attrs = coffees[coffee];
  61. if (attrs.in_stock > 0) {
  62. results.push(`${coffee} has ${attrs.in_stock}`);
  63. }
  64. }
  65. return results;
  66. })();
  67. console.log(to_print.join(", "));
  68. //# sourceMappingURL=4-4-objects.js.map