Advertisement
Guest User

Untitled

a guest
Jan 11th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>JS Bin</title>
  7. </head>
  8. <body>
  9.  
  10. <script id="jsbin-javascript">
  11. // Array.prototype.map()
  12. /*
  13. The map() method creates a new array with the results of calling a
  14. provided function on every element in this array.
  15.  
  16. Return value:
  17. A new array with each element being the result of the callback function.
  18. */
  19.  
  20. var numbers = [1, 2, 3];
  21. var roots = numbers.map(function(x){
  22. return x * x * x;
  23. });
  24. // roots is now [1, 8, 27]
  25. // numbers is still [1, 2, 3]
  26.  
  27.  
  28. function map(array, callbackFunction) {
  29. var newArray = [];
  30. array.forEach(function(element) {
  31. newArray.push(callbackFunction(element));
  32. });
  33. return newArray;
  34. }
  35.  
  36. function cubeAll(numbers) {
  37. return map(numbers, function(n) {
  38. return n * n * n;
  39. });
  40. }
  41.  
  42. function cube(n) {
  43. return n * n * n;
  44. }
  45.  
  46. console.log(cubeAll([1, 2, 3]));
  47. console.log(map([1, 2, 3], cube));
  48. </script>
  49.  
  50.  
  51.  
  52. <script id="jsbin-source-javascript" type="text/javascript">// Array.prototype.map()
  53. /*
  54. The map() method creates a new array with the results of calling a
  55. provided function on every element in this array.
  56.  
  57. Return value:
  58. A new array with each element being the result of the callback function.
  59. */
  60.  
  61. var numbers = [1, 2, 3];
  62. var roots = numbers.map(function(x){
  63. return x * x * x;
  64. });
  65. // roots is now [1, 8, 27]
  66. // numbers is still [1, 2, 3]
  67.  
  68.  
  69. function map(array, callbackFunction) {
  70. var newArray = [];
  71. array.forEach(function(element) {
  72. newArray.push(callbackFunction(element));
  73. });
  74. return newArray;
  75. }
  76.  
  77. function cubeAll(numbers) {
  78. return map(numbers, function(n) {
  79. return n * n * n;
  80. });
  81. }
  82.  
  83. function cube(n) {
  84. return n * n * n;
  85. }
  86.  
  87. console.log(cubeAll([1, 2, 3]));
  88. console.log(map([1, 2, 3], cube));</script></body>
  89. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement