hw_15_04_universal_string .html 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <header>
  2. string
  3. </header>
  4. <body>
  5. <script>
  6. function walker(parent) {
  7. let res = "";
  8. let isObject = parent != null && typeof parent === "object";
  9. let isArray = Array.isArray(parent);
  10. if (isArray) {
  11. res += "[";
  12. }
  13. else if (isObject) {
  14. res += "{";
  15. }
  16. else {
  17. res += `"${parent}"`;
  18. }
  19. if (isObject || isArray) {
  20. let childArr = [];
  21. for (let el in parent) {
  22. let childStr = `${walker(parent[el])}`; // разбор вложенного значения єлемента
  23. if (!isArray) {
  24. childStr = `"${el}":${childStr}`;
  25. }
  26. childArr.push(childStr);
  27. }
  28. res += childArr.join(",");
  29. }
  30. if (isArray) {
  31. res += "]";
  32. }
  33. else if (isObject) {
  34. res += "}";
  35. }
  36. return res;
  37. }
  38. const table = {
  39. tagName: 'table',
  40. attrs: {
  41. border: "1",
  42. },
  43. children: [
  44. {
  45. tagName: 'tr',
  46. children: [
  47. {
  48. tagName: "td",
  49. children: ["1x1"],
  50. },
  51. {
  52. tagName: "td",
  53. children: ["1x2"],
  54. },
  55. ]
  56. },
  57. {
  58. tagName: 'tr',
  59. children: [
  60. {
  61. tagName: "td",
  62. children: ["2x1"],
  63. },
  64. {
  65. tagName: "td",
  66. children: ["2x2"],
  67. },
  68. ]
  69. }
  70. ]
  71. }
  72. var objStr = walker(table);
  73. var obj = JSON.parse(objStr);
  74. document.write(objStr);
  75. var testObjStr = JSON.stringify(table);
  76. if (objStr != testObjStr)
  77. alert("Khren'");
  78. </script>
  79. </body>