Created
May 12, 2025 08:20
-
-
Save hmel1990/84d0bce6d4fe495673490c02f327eafd to your computer and use it in GitHub Desktop.
ObjectsAndFunctionsDZ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title> | |
</head> | |
<body> | |
<h1>Демонстрация работы с массивами</h1> | |
<p id="output"></p> | |
<p id="output2"></p> | |
<!--Задание 1--> | |
<!--Создать массив «список покупок». Каждый элемент массива является объектом,--> | |
<!--который содержит название товара, необходимое количество и то, был ли он куплен или нет.--> | |
<!--Напишите несколько функций для работы с таким массивом.--> | |
<!--Вывод всего списка на экран таким образом, чтобы сначала шли не купленные товары, а потом купленные.--> | |
<!--Добавление покупки в список. | |
Обратите внимание, что при добавлении покупки с уже существующим товаром в списке, | |
нужно увеличить количество в существующей покупке, а не добавлять новую.--> | |
<!--Приобретение товара. Функция получает название товара и помечает его как купленный.--> | |
<script> | |
const output = document.getElementById('output'); | |
let outputText = ''; | |
let shoppingList = | |
[ | |
{ name: "Хлеб", quantity: 2, bought: true }, | |
{ name: "Молоко", quantity: 1, bought: false }, | |
{ name: "Яблоки", quantity: 6, bought: true }, | |
{ name: "Кофе", quantity: 0, bought: false }, | |
]; | |
function showShoppingList(shoppingList) | |
{ | |
let list = shoppingList.filter(item => item.bought === true).concat | |
(shoppingList.filter(item => item.bought === false)); | |
let out = list.map(item => | |
`Товар: ${item.name}, Кол-во: ${item.quantity}, Куплен: ${item.bought ? "Да" : "Нет"}`+ '<br>' | |
).join('\n'); | |
outputText +=out; | |
} | |
function addToShoppingList(shoppingList, shoppingItem) | |
{ | |
let shoppingItemExists = shoppingList.find(item => item.name === shoppingItem.name); | |
if (shoppingItemExists) { | |
if (!shoppingItemExists.bought) shoppingItemExists.bought = true; | |
shoppingItemExists.quantity += shoppingItem.quantity; // на тот случай если товара будет несколько едениц | |
} else { | |
shoppingList.push(shoppingItem); | |
} | |
} | |
addToShoppingList (shoppingList, {name: "Сахар",quantity: 2, bought: true}) | |
addToShoppingList (shoppingList, {name: "Хлеб",quantity: 2, bought: true}) | |
function itemBought(shoppingList, itemName) | |
{ | |
let shoppingItemExists = shoppingList.find(item => item.name === itemName); | |
if (shoppingItemExists) | |
{ | |
shoppingItemExists.bought = true; | |
if (shoppingItemExists.quantity === 0) shoppingItemExists.quantity = 1; // если товар куплен то хотя бы в одном екземлпяре его количество должно быть | |
} | |
else | |
{ | |
// alert ("такого товара нет в списке"); | |
} | |
} | |
showShoppingList (shoppingList); | |
outputText += '<br>'; | |
itemBought (shoppingList, "Кофе"); | |
itemBought (shoppingList, "Кокос"); | |
showShoppingList (shoppingList); | |
output.innerHTML = outputText; | |
</script> | |
<!-- Создать массив из 10 случайных чисел и написать несколько функций для работы с ним. | |
Функция принимает массив и выводит его на экран. | |
Функция принимает массив и выводит только четные элементы. | |
Функция принимает массив и возвращает сумму всех элементов массива.--> | |
<!--Написать функцию, которая считает среднюю длину слова в предложении--> | |
<script> | |
const output2 = document.getElementById('output2'); | |
let outputText2 = ''; | |
function averageWordLength (sentence) | |
{ | |
sentence = sentence.replace('.',''); | |
let arrWords = sentence.trim().split(' '); | |
let arrAverageSymbols = arrWords.map(item => item.length).reduce((acc, curr) => acc + curr, 0); | |
let average = arrAverageSymbols/arrWords.length; | |
outputText2 +='<br>'+`Выводим среднюю длину слова в массиве на печать: ${average.toFixed(0)}`; | |
} | |
averageWordLength ("А роза упала на лапу Азора."); | |
let arr = []; | |
for (let i = 0; i < 9; i++) | |
{ | |
let random = Math.floor(Math.random() * 11); // 0–10 | |
arr.push(random); | |
} | |
function showArray (arr) | |
{ | |
outputText2 += '<br>'+`Выводим массив на печать: ${arr.join(', ')}`; | |
} | |
showArray(arr); | |
// Функция принимает массив и выводит только четные элементы. | |
function showArrayOdd (arr) | |
{ | |
outputText2 += '<br>'+`Выводим четные элементы массива на печать: ${arr.filter(item=> item%2===0&& item!=0).join(', ')}`; | |
} | |
showArrayOdd(arr); | |
function sumArray (arr) | |
{ | |
outputText2 += '<br>'+`Выводим сумму элементов массива на печать: ${arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0)}`; | |
} | |
sumArray(arr); | |
output2.innerHTML = outputText2; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment