4-1-arrays.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var geoLocate, i, index, j, len, len1, loc, location, storeLocations1, storeLocations2, storeLocations3;
  2. storeLocations1 = ['Orlando', 'Winter Park', 'Sanford'];
  3. // Beware, this doesn't compile correctly:
  4. // storeLocations.forEach(location, index) ->
  5. // It uses it as a forEach(location, index) call with a () => {} callback
  6. // So be sure to add the space.
  7. storeLocations1.forEach(function(location, index) {
  8. return console.log(`Location ${index}: ${location}`);
  9. });
  10. // Or use something more idiomatic:
  11. for (index = i = 0, len = storeLocations1.length; i < len; index = ++i) {
  12. location = storeLocations1[index];
  13. console.log(`Location ${index}: ${location}`);
  14. }
  15. for (index = j = 0, len1 = storeLocations1.length; j < len1; index = ++j) {
  16. location = storeLocations1[index];
  17. // List comprehensions
  18. console.log(`Location ${index}: ${location}`);
  19. }
  20. // In this case, the parentheses are essential
  21. storeLocations2 = (function() {
  22. var k, len2, results;
  23. results = [];
  24. for (k = 0, len2 = storeLocations1.length; k < len2; k++) {
  25. loc = storeLocations1[k];
  26. results.push(`${loc}, FL`);
  27. }
  28. return results;
  29. })();
  30. // Without them, the whole "storeLocations = ..." part is run for each loc.
  31. console.log(storeLocations2);
  32. geoLocate = function(loc) {
  33. return `${loc}, USA`;
  34. };
  35. // Applying a filter to a list comprehension
  36. console.log((function() {
  37. var k, len2, results;
  38. results = [];
  39. for (k = 0, len2 = storeLocations1.length; k < len2; k++) {
  40. loc = storeLocations1[k];
  41. if (loc !== 'Sanford') {
  42. results.push(geoLocate(loc));
  43. }
  44. }
  45. return results;
  46. })());
  47. storeLocations3 = (function() {
  48. var k, len2, results;
  49. results = [];
  50. for (k = 0, len2 = storeLocations1.length; k < len2; k++) {
  51. loc = storeLocations1[k];
  52. if (loc !== 'Sanford') {
  53. results.push(loc);
  54. }
  55. }
  56. return results;
  57. })();
  58. console.log(storeLocations3);
  59. //# sourceMappingURL=4-1-arrays.js.map