Dz8js.html 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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(arr, key, boolean = true) {
  19. arr.sort(bool)
  20. function bool(a, b) {
  21. if (boolean) {
  22. return (a[key] > b[key]) ? 1 : -1;
  23. }
  24. else {
  25. return (a[key] < b[key]) ? 1 : -1;
  26. }
  27. }
  28. return arr;
  29. }
  30. sort(persons, "name")
  31. //array map
  32. let array = ["1", {}, null, undefined, "500", 700]
  33. let y = array.map(x => {
  34. let number = Number(x)
  35. return isNaN(x) ? x : number
  36. })
  37. console.log(y)
  38. //array reduce
  39. let array = ["0", 5, 3, "string", null]
  40. let result = array.reduce((a, b) =>
  41. typeof (b) === "number" ? a * b : a, 1
  42. )
  43. console.log(result);
  44. //object filter
  45. var phone = {
  46. brand: "meizu",
  47. model: "m2",
  48. ram: 2,
  49. color: "black",
  50. };
  51. filter(phone, (key, value) => key == "color" || value == 2);
  52. function filter(obj, key, value) {
  53. let newObj = {}
  54. for (let key in obj) {
  55. for (let value in obj) {
  56. if (obj[key] == 2 && value == "color") {
  57. newObj[key] = obj[key]
  58. newObj[value] = obj[value]
  59. }
  60. }
  61. }
  62. return newObj
  63. }
  64. //object map
  65. function map(obj, callback) {
  66. let result1 = {};
  67. for (let key in obj) {
  68. result1 = { ...result1, ...callback(key, obj[key]) }
  69. }
  70. return result1
  71. }
  72. let miniObj = map({ name: "Иван", age: 17 }, function (key, value) {
  73. var result = {};
  74. result[key + "_"] = value + "$";
  75. return result;
  76. })
  77. console.log(miniObj)
  78. //Sum
  79. function sum (min, max, step){
  80. if(max <= 0){
  81. return 0
  82. }
  83. return sum (min +step, max -1, step) + min
  84. }
  85. console.log(sum(1,5,3))
  86. </script>
  87. </body>
  88. </html>