*/
// Сделайте декларативную JSON-структуру для тэгов выше, в которой:
// каждый тэг будет объектом
// имя тэга будет полем tagName
// вложенные тэги будут в поле subTags
// текст в тэге будет в поле text
// набор аттрибутов тэга будет в поле attrs.
// Выведите значения текста во второй кнопке, используя . и [].
// Выведите значение атрибута id во втором input, используя . и [].
let body = {
tagName: 'body',
subTags: {
div1: {
tagName: 'div',
subTags: {
span: {
tagName: 'span',
text: 'Enter a data please:',
},
br: {
tagName: 'br',
},
input: {
tagName: 'input',
attrs: {
type: 'text',
id: 'name',
},
},
input: {
tagName: 'input',
attrs: {
type: 'text',
id: 'surname',
},
},
},
},
div2: {
tagName: 'div',
subTags: {
button: {
tagName: 'button',
attrs: {
id: 'ok',
},
text: 'OK',
},
button: {
tagName: 'button',
attrs: {
id: 'cancel',
},
text: 'Cancel',
},
},
},
},
}
console.log(body.subTags.div2.subTags.button.text);
console.log(body['subTags']['div2']['subTags']['button']['text']);
console.log(body.subTags.div1.subTags.input.attrs.id);
console.log(body['subTags']['div1']['subTags']['input']['attrs']['id']);
// P.S. Не уверен, правильно ли менять названия тегов дива на див1 и див2, но так работает)
// declarative fields
// Как известно, элемент массива и объекта может быть любого типа данных JS, т. е. в коде может быть любое выражение,
// которое вычисляется в то или иное значение типа данных.
// А значит, мы можем применять функции для ввода данных типа confirm или prompt:
// var text = "Enter a number";
// var arr3 = [+prompt(text), +prompt(text), +prompt(text)]; //вводим числа.
// Организуйте таким способом заполнение полей в объектах:
var notebook = {
brand: "HP",
type: "440 G4",
model: "Y7Z75EA",
ram: 4,
size: "14",
weight: 1.8,
resolution: {
width: 1920,
height: 1080,
},
};
var phone = {
brand: "meizu",
model: "m2",
ram: 2,
color: "black",
};
var person = {
name: "Donald",
surname: "Trump",
married: true,
}
// Например:
// var person = {
// name: prompt("Enter a name"),
// surname: prompt("Enter a surname"),
// }
// Используйте приведение к числу, prompt и confirm в зависимости от типов данных.
var notebook = {
brand: prompt('Enter the laptop brand:'),
type: prompt('Enter the type of laptop:'),
model: prompt('Enter the model of the laptop:'),
ram: +prompt('Enter the value of RAM:'),
size: prompt('Enter the size of screen of laptop:'),
weight: +prompt('Enter the weight of laptop:'),
resolution: {
width: +prompt('Enter the width of the screen:'),
height: +prompt('Enter the height of the screen:'),
},
};
var phone = {
brand: prompt('Enter the cell phone brand:'),
model: prompt('Enter the cell phone model:'),
ram: +prompt('Enter the value of ram:'),
color: prompt('Enter the color of the cell phone: '),
};
var person = {
name: prompt('Enter the name of the person:'),
surname: prompt('Enter the surname of the person:'),
married: window.confirm('Is the person married?'),
}
// object links
// Добавьте персоне гаджеты, используя новые поля smartphone и laptop в объекте персоны
// Добавьте владельца в гаджеты, используя новое поле owner в объектах телефона и ноутбука.
// обратите внимание на цикличность ссылок в объектах, если вы все сделали правильно, то
// person.smartphone.owner.laptop.owner.smartphone == person.smartphone
var notebook = {
brand: prompt('Enter the laptop brand:'),
type: prompt('Enter the type of laptop:'),
model: prompt('Enter the model of the laptop:'),
ram: +prompt('Enter the value of RAM:'),
size: prompt('Enter the size of screen of laptop:'),
weight: +prompt('Enter the weight of laptop:'),
resolution: {
width: +prompt('Enter the width of the screen:'),
height: +prompt('Enter the height of the screen:'),
},
};
var phone = {
brand: prompt('Enter the cell phone brand:'),
model: prompt('Enter the cell phone model:'),
ram: +prompt('Enter the value of ram:'),
color: prompt('Enter the color of the cell phone: '),
};
var person = {
name: prompt('Enter the name of the person:'),
surname: prompt('Enter the surname of the person:'),
married: window.confirm('Is the person married?'),
}
notebook.owner = person,
phone.owner = person,
person.smartphone = phone,
person.laptop = notebook,
alert(person.smartphone.owner.laptop.owner.smartphone == person.smartphone);
// imperative array fill 3
// Создайте пустой массив и добавьте в него три элемента, введенные пользователем (prompt),
// используя императивный подход (несколько операторов подряд)
var arr = []
arr[0] = prompt('Enter the element #1:');
arr[1] = prompt('Enter the element #2:');
arr[2] = prompt('Enter the element #3:');
console.log(arr);
// while confirm
// Сделайте цикл с confirm, который продолжается по Отмена и заканчивается по ОК.
var fact = false;
while (fact == false) {
fact = window.confirm('putin lox?');
}
// array fill
// Создайте пустой массив и добавляйте в него элементы, пока пользователь не нажмет Отмена в очередном prompt.
// Используйте push для удобства: push
var arr = [];
var add = '';
while (add != null) {
add = prompt('Write anything here...');
arr.push(add);
}
console.log(arr);
// array fill nopush
// Сделайте предыдущее задание, не используя push, а обращаясь к элементам по индексу.
var arr = [];
var add = '';
while (add != null) {
add = prompt('Write anything here...');
arr[arr.length] = add;
}
console.log(arr);
// infinite probability
// Создайте бесконечный цикл, который прерывается с помощью конструкции break, когда Math.random() > 0.9.
// Код должен подсчитывать количество итераций и вывести это число с помощью alert.
var counter = 0;
while (Math.random() < 0.9) {
counter++;
if (Math.random() > 0.9) {
break;
}
}
alert(counter);
// empty loop
// Сделайте цикл с prompt, который прерывается по нажатию OK и продолжается по нажатию "Отмена" c пустым телом цикла.
for (var god = prompt('Do you believe in god?'); god == null; god = prompt('Do you believe in god?')) { }
// progression sum
// Подсчитать сумму арифметической прогрессии от 1 до N c шагом 3 (1,4,7....) используя цикл for.
var sum;
for (let i = 1, j = i + 3, n = +prompt('Enter the N:'); j < n; i = i + 3, j = i + 3, sum = i + j) { }
alert(sum);
// chess one line
// Сформировать строку " # # # # # " с помощью цикла for. Длина строки может быть четной и нечетной, и указывается в одном месте в коде.
var str;
for (str = [''], n = +prompt('Enter the length of the string:'); str.length < (n / 2); str.push('#')) { }
console.log(str.join(' '))
// numbers
// Сформировать строку c помощью вложенных циклов. Для перевода строки используйте \n.
var arr1 = [];
var arr2 = [0]
for (let m = 0; m < 10; m++) {
for (arr2, n = 0; arr2.length < 10; arr2.push(n + 1), n++) { }
arr1 += ((arr2.join('')) + '\n');
}
console.log(arr1)
// chess
// Сформируйте строку с шахматной доской из вложенных циклов. Для перевода строки используйте \n. Код должен поддерживать легкое изменение размеров доски.
// .#.#.#.#.#.#
// #.#.#.#.#.#.
// .#.#.#.#.#.#
// #.#.#.#.#.#.
// .#.#.#.#.#.#
// #.#.#.#.#.#.
// .#.#.#.#.#.#
// #.#.#.#.#.#.
// .#.#.#.#.#.#
// #.#.#.#.#.#.
var chessBoard = "";
let rows = +prompt('Enter the amount of rows:');
let cols = +prompt('Enter the amount of columns:');
for (var j = 1; j <= cols; j += 1) {
if (j % 2 != 0) {
for (var i = 1; i <= rows; i += 1) {
if ((i % (cols + 1)) == 0) {
chessBoard += "\n";
} else if (i % 2 != 0) {
chessBoard += "#";
} else {
chessBoard += ".";
}
}
chessBoard += "\n";
}
else {
for (var i = 1; i <= rows; i += 1) {
if ((i % (cols + 1)) == 0) {
chessBoard += "\n";
} else if (i % 2 != 0) {
chessBoard += ".";
} else {
chessBoard += "#";
}
}
chessBoard += "\n";
}
}
console.log(chessBoard);
// cubes
// Сформируйте массив из N элементов, содержащий в себе кубы индексов, т. е:
// [0,1,8,27,64...]
var cubes = [];
var n = prompt('Enter the amount of items:')
for (i = 0; i < n; i++) {
cubes.push(Math.pow(i, 3));
}
console.log(cubes);
// multiply table
// C помощью вложенного цикла сформируйте массив массивов "таблица умножения". Для инициализации вложенных массивов используйте
// arr[i] = [] //в i-тый элемент массива заносится новый пустой массив
// arr[5][6] должен быть равен, соответственно, 30, arr[7][2] == 14 и так далее.
var m = [];
for (var i = 0; i < 10; i++) {
var n = [];
for (var j = 0; j < 10; j++) {
n.push(j * i);
}
m.push(n);
}
console.log(m[1][1]);
// matrix to html table
// Сделайте вложенный цикл, который формирует HTML-таблицу в переменной строкового типа из любого двумерного массива.
// Т. е. если в нём использовать результат работы предыдущего задания, то получится таблица умножения в HTML
var table = "
";
var m = [];
for (var i = 0; i < 10; i++) {
var n = [];
table += `