index.html 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script>
  11. // -----------------------sort
  12. var persons = [
  13. { name: "Иван", age: 17 },
  14. { name: "Мария", age: 35 },
  15. { name: "Алексей", age: 73 },
  16. { name: "Яков", age: 12 },
  17. ];
  18. function sort(array, objectKey, boolean) {
  19. if (boolean) {
  20. array.sort((a, b) =>
  21. a[objectKey] < b[objectKey] ? 1 : -1
  22. );
  23. } else {
  24. array.sort((a, b) =>
  25. a[objectKey] > b[objectKey] ? 1 : -1
  26. );
  27. }
  28. }
  29. // sort(persons, "age")
  30. sort(persons, "name", false);
  31. // ------------------------array map
  32. var array = ["1", {}, null, undefined, "500", 700];
  33. // array.map( a => (a === Number ? +a : a))
  34. let b = array.map((a) => {
  35. let number = Number(a);
  36. return isNaN(a) ? a : number;
  37. });
  38. console.log(b);
  39. // ------------------------array reduce
  40. var array2 = ["0", 5, 3, "string", null];
  41. let productNumber = array2.reduce(function (a, b) {
  42. if (typeof b === "number") {
  43. a *= b;
  44. }
  45. return a;
  46. }, 1);
  47. console.log(productNumber);
  48. // ------------------------object filter
  49. var phone = {
  50. brand: "meizu",
  51. model: "m2",
  52. ram: 2,
  53. color: "black",
  54. };
  55. function filter(obj, callback) {
  56. let newObj = {};
  57. for (let key in obj) {
  58. if (callback(key, obj[key])) {
  59. newObj = { ...newObj, [key]: obj[key] };
  60. }
  61. }
  62. return newObj;
  63. }
  64. filter(phone, (key, value) => key === "color" || value === 2);
  65. //-----------------------object map
  66. function map(obj, callBack) {
  67. let result = {};
  68. for (let key in obj) {
  69. result = { ...result, ...callBack(key, obj[key]) };
  70. return result;
  71. }
  72. }
  73. map({ name: "Иван", age: 17 }, function (key, value) {
  74. var result = {};
  75. result[key + "_"] = value + "$";
  76. return result;
  77. }); //должен вернуть {name_: "Иван$", age_: "17$"}
  78. //-----------------------Рекурсия
  79. function progression_sum(max_num_in_progressian) {
  80. if (max_num_in_progressian === 1) return 1;
  81. console.log(max_num_in_progressian);
  82. let result =
  83. progression_sum(max_num_in_progressian - 1) +
  84. max_num_in_progressian;
  85. console.log(max_num_in_progressian, result);
  86. return result;
  87. }
  88. console.log(progression_sum(5));
  89. </script>
  90. </body>
  91. </html>