App.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /* <body>
  2. <div>
  3. <span>Enter a data please:</span><br/>
  4. <input type='text' id='name'>
  5. <input type='text' id='surname'>
  6. </div>
  7. <div>
  8. <button id='ok'>OK</button>
  9. <button id='cancel'>Cancel</button>
  10. </div>
  11. </body>
  12. */
  13. // Сделайте декларативную JSON-структуру для тэгов выше, в которой:
  14. // каждый тэг будет объектом
  15. // имя тэга будет полем tagName
  16. // вложенные тэги будут в поле subTags
  17. // текст в тэге будет в поле text
  18. // набор аттрибутов тэга будет в поле attrs.
  19. // Выведите значения текста во второй кнопке, используя . и [].
  20. // Выведите значение атрибута id во втором input, используя . и [].
  21. let body = {
  22. tagName: 'body',
  23. subTags: {
  24. div1: {
  25. tagName: 'div',
  26. subTags: {
  27. span: {
  28. tagName: 'span',
  29. text: 'Enter a data please:',
  30. },
  31. br: {
  32. tagName: 'br',
  33. },
  34. input: {
  35. tagName: 'input',
  36. attrs: {
  37. type: 'text',
  38. id: 'name',
  39. },
  40. },
  41. input: {
  42. tagName: 'input',
  43. attrs: {
  44. type: 'text',
  45. id: 'surname',
  46. },
  47. },
  48. },
  49. },
  50. div2: {
  51. tagName: 'div',
  52. subTags: {
  53. button: {
  54. tagName: 'button',
  55. attrs: {
  56. id: 'ok',
  57. },
  58. text: 'OK',
  59. },
  60. button: {
  61. tagName: 'button',
  62. attrs: {
  63. id: 'cancel',
  64. },
  65. text: 'Cancel',
  66. },
  67. },
  68. },
  69. },
  70. }
  71. console.log(body.subTags.div2.subTags.button.text);
  72. console.log(body['subTags']['div2']['subTags']['button']['text']);
  73. console.log(body.subTags.div1.subTags.input.attrs.id);
  74. console.log(body['subTags']['div1']['subTags']['input']['attrs']['id']);
  75. // P.S. Не уверен, правильно ли менять названия тегов дива на див1 и див2, но так работает)
  76. // declarative fields
  77. // Как известно, элемент массива и объекта может быть любого типа данных JS, т. е. в коде может быть любое выражение,
  78. // которое вычисляется в то или иное значение типа данных.
  79. // А значит, мы можем применять функции для ввода данных типа confirm или prompt:
  80. // var text = "Enter a number";
  81. // var arr3 = [+prompt(text), +prompt(text), +prompt(text)]; //вводим числа.
  82. // Организуйте таким способом заполнение полей в объектах:
  83. var notebook = {
  84. brand: "HP",
  85. type: "440 G4",
  86. model: "Y7Z75EA",
  87. ram: 4,
  88. size: "14",
  89. weight: 1.8,
  90. resolution: {
  91. width: 1920,
  92. height: 1080,
  93. },
  94. };
  95. var phone = {
  96. brand: "meizu",
  97. model: "m2",
  98. ram: 2,
  99. color: "black",
  100. };
  101. var person = {
  102. name: "Donald",
  103. surname: "Trump",
  104. married: true,
  105. }
  106. // Например:
  107. // var person = {
  108. // name: prompt("Enter a name"),
  109. // surname: prompt("Enter a surname"),
  110. // }
  111. // Используйте приведение к числу, prompt и confirm в зависимости от типов данных.
  112. var notebook = {
  113. brand: prompt('Enter the laptop brand:'),
  114. type: prompt('Enter the type of laptop:'),
  115. model: prompt('Enter the model of the laptop:'),
  116. ram: +prompt('Enter the value of RAM:'),
  117. size: prompt('Enter the size of screen of laptop:'),
  118. weight: +prompt('Enter the weight of laptop:'),
  119. resolution: {
  120. width: +prompt('Enter the width of the screen:'),
  121. height: +prompt('Enter the height of the screen:'),
  122. },
  123. };
  124. var phone = {
  125. brand: prompt('Enter the cell phone brand:'),
  126. model: prompt('Enter the cell phone model:'),
  127. ram: +prompt('Enter the value of ram:'),
  128. color: prompt('Enter the color of the cell phone: '),
  129. };
  130. var person = {
  131. name: prompt('Enter the name of the person:'),
  132. surname: prompt('Enter the surname of the person:'),
  133. married: window.confirm('Is the person married?'),
  134. }
  135. // object links
  136. // Добавьте персоне гаджеты, используя новые поля smartphone и laptop в объекте персоны
  137. // Добавьте владельца в гаджеты, используя новое поле owner в объектах телефона и ноутбука.
  138. // обратите внимание на цикличность ссылок в объектах, если вы все сделали правильно, то
  139. // person.smartphone.owner.laptop.owner.smartphone == person.smartphone
  140. var notebook = {
  141. brand: prompt('Enter the laptop brand:'),
  142. type: prompt('Enter the type of laptop:'),
  143. model: prompt('Enter the model of the laptop:'),
  144. ram: +prompt('Enter the value of RAM:'),
  145. size: prompt('Enter the size of screen of laptop:'),
  146. weight: +prompt('Enter the weight of laptop:'),
  147. resolution: {
  148. width: +prompt('Enter the width of the screen:'),
  149. height: +prompt('Enter the height of the screen:'),
  150. },
  151. };
  152. var phone = {
  153. brand: prompt('Enter the cell phone brand:'),
  154. model: prompt('Enter the cell phone model:'),
  155. ram: +prompt('Enter the value of ram:'),
  156. color: prompt('Enter the color of the cell phone: '),
  157. };
  158. var person = {
  159. name: prompt('Enter the name of the person:'),
  160. surname: prompt('Enter the surname of the person:'),
  161. married: window.confirm('Is the person married?'),
  162. }
  163. notebook.owner = person,
  164. phone.owner = person,
  165. person.smartphone = phone,
  166. person.laptop = notebook,
  167. alert(person.smartphone.owner.laptop.owner.smartphone == person.smartphone);
  168. // imperative array fill 3
  169. // Создайте пустой массив и добавьте в него три элемента, введенные пользователем (prompt),
  170. // используя императивный подход (несколько операторов подряд)
  171. var arr = []
  172. arr[0] = prompt('Enter the element #1:');
  173. arr[1] = prompt('Enter the element #2:');
  174. arr[2] = prompt('Enter the element #3:');
  175. console.log(arr);
  176. // while confirm
  177. // Сделайте цикл с confirm, который продолжается по Отмена и заканчивается по ОК.
  178. var fact = false;
  179. while (fact == false) {
  180. fact = window.confirm('putin lox?');
  181. }
  182. // array fill
  183. // Создайте пустой массив и добавляйте в него элементы, пока пользователь не нажмет Отмена в очередном prompt.
  184. // Используйте push для удобства: push
  185. var arr = [];
  186. var add = '';
  187. while (add != null) {
  188. add = prompt('Write anything here...');
  189. arr.push(add);
  190. }
  191. console.log(arr);
  192. // array fill nopush
  193. // Сделайте предыдущее задание, не используя push, а обращаясь к элементам по индексу.
  194. var arr = [];
  195. var add = '';
  196. while (add != null) {
  197. add = prompt('Write anything here...');
  198. arr[arr.length] = add;
  199. }
  200. console.log(arr);
  201. // infinite probability
  202. // Создайте бесконечный цикл, который прерывается с помощью конструкции break, когда Math.random() > 0.9.
  203. // Код должен подсчитывать количество итераций и вывести это число с помощью alert.
  204. var counter = 0;
  205. while (Math.random() < 0.9) {
  206. counter++;
  207. if (Math.random() > 0.9) {
  208. break;
  209. }
  210. }
  211. alert(counter);
  212. // empty loop
  213. // Сделайте цикл с prompt, который прерывается по нажатию OK и продолжается по нажатию "Отмена" c пустым телом цикла.
  214. for (var god = prompt('Do you believe in god?'); god == null; god = prompt('Do you believe in god?')) { }
  215. // progression sum
  216. // Подсчитать сумму арифметической прогрессии от 1 до N c шагом 3 (1,4,7....) используя цикл for.
  217. var sum;
  218. for (let i = 1, j = i + 3, n = +prompt('Enter the N:'); j < n; i = i + 3, j = i + 3, sum = i + j) { }
  219. alert(sum);
  220. // chess one line
  221. // Сформировать строку " # # # # # " с помощью цикла for. Длина строки может быть четной и нечетной, и указывается в одном месте в коде.
  222. var str;
  223. for (str = [''], n = +prompt('Enter the length of the string:'); str.length < (n / 2); str.push('#')) { }
  224. console.log(str.join(' '))
  225. // numbers
  226. // Сформировать строку c помощью вложенных циклов. Для перевода строки используйте \n.
  227. var arr1 = [];
  228. var arr2 = [0]
  229. for (let m = 0; m < 10; m++) {
  230. for (arr2, n = 0; arr2.length < 10; arr2.push(n + 1), n++) { }
  231. arr1 += ((arr2.join('')) + '\n');
  232. }
  233. console.log(arr1)
  234. // chess
  235. // Сформируйте строку с шахматной доской из вложенных циклов. Для перевода строки используйте \n. Код должен поддерживать легкое изменение размеров доски.
  236. // .#.#.#.#.#.#
  237. // #.#.#.#.#.#.
  238. // .#.#.#.#.#.#
  239. // #.#.#.#.#.#.
  240. // .#.#.#.#.#.#
  241. // #.#.#.#.#.#.
  242. // .#.#.#.#.#.#
  243. // #.#.#.#.#.#.
  244. // .#.#.#.#.#.#
  245. // #.#.#.#.#.#.
  246. var chessBoard = "";
  247. let rows = +prompt('Enter the amount of rows:');
  248. let cols = +prompt('Enter the amount of columns:');
  249. for (var j = 1; j <= cols; j += 1) {
  250. if (j % 2 != 0) {
  251. for (var i = 1; i <= rows; i += 1) {
  252. if ((i % (cols + 1)) == 0) {
  253. chessBoard += "\n";
  254. } else if (i % 2 != 0) {
  255. chessBoard += "#";
  256. } else {
  257. chessBoard += ".";
  258. }
  259. }
  260. chessBoard += "\n";
  261. }
  262. else {
  263. for (var i = 1; i <= rows; i += 1) {
  264. if ((i % (cols + 1)) == 0) {
  265. chessBoard += "\n";
  266. } else if (i % 2 != 0) {
  267. chessBoard += ".";
  268. } else {
  269. chessBoard += "#";
  270. }
  271. }
  272. chessBoard += "\n";
  273. }
  274. }
  275. console.log(chessBoard);
  276. // cubes
  277. // Сформируйте массив из N элементов, содержащий в себе кубы индексов, т. е:
  278. // [0,1,8,27,64...]
  279. var cubes = [];
  280. var n = prompt('Enter the amount of items:')
  281. for (i = 0; i < n; i++) {
  282. cubes.push(Math.pow(i, 3));
  283. }
  284. console.log(cubes);
  285. // multiply table
  286. // C помощью вложенного цикла сформируйте массив массивов "таблица умножения". Для инициализации вложенных массивов используйте
  287. // arr[i] = [] //в i-тый элемент массива заносится новый пустой массив
  288. // arr[5][6] должен быть равен, соответственно, 30, arr[7][2] == 14 и так далее.
  289. var m = [];
  290. for (var i = 0; i < 10; i++) {
  291. var n = [];
  292. for (var j = 0; j < 10; j++) {
  293. n.push(j * i);
  294. }
  295. m.push(n);
  296. }
  297. console.log(m[1][1]);
  298. // matrix to html table
  299. // Сделайте вложенный цикл, который формирует HTML-таблицу в переменной строкового типа из любого двумерного массива.
  300. // Т. е. если в нём использовать результат работы предыдущего задания, то получится таблица умножения в HTML
  301. var table = "<table border='1'>";
  302. var m = [];
  303. for (var i = 0; i < 10; i++) {
  304. var n = [];
  305. table += `<tr>`;
  306. for (var j = 0; j < 10; j++) {
  307. n.push(j * i);
  308. table += `<td>${i}*${j}=${i*j}</td>`;
  309. }
  310. table += `</tr>`
  311. m.push(n);
  312. }
  313. table += "</table>";
  314. document.write(table);