Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Задача 1. Профиль пользователя
- let profile = {
- firstName: 'Иван',
- lastName: 'Иванов',
- age: 30
- };
- profile.fullName = profile.firstName + ' ' + profile.lastName;
- console.log(profile.fullName, profile.age);
- // Иван Иванов 30
- // Задача 2. Корзина товаров
- let cart = { items: [], total: 0 };
- function addItem(name, price) {
- cart.items.push({ name: name, price: price });
- cart.total += price;
- }
- addItem('Apple', 50);
- addItem('Banana', 30);
- console.log(cart.items, cart.total);
- // [{name:'Apple',price:50},{name:'Banana',price:30}] 80
- // Задача 3. Удаление неактивных
- let users = {
- user1: { active: true },
- user2: { active: false },
- user3: { active: false },
- user4: { active: true }
- };
- function removeInactive(userObj) {
- for (let key in userObj) {
- if (userObj[key].active === false) {
- delete userObj[key];
- }
- }
- }
- removeInactive(users);
- console.log(users);
- // { user1: {active:true}, user4: {active:true} }
- // Задача 4. Подсчёт свойств
- function countProps(obj) {
- return Object.keys(obj).length;
- }
- console.log(countProps({a:1, b:2, c:3})); // 3
- console.log(countProps({})); // 0
- // Задача 5. Копия объекта
- let orig = { a: 1, b: 2 };
- let copy = {};
- for (let key in orig) {
- if (orig.hasOwnProperty(key)) {
- copy[key] = orig[key];
- }
- }
- copy.a = 10;
- console.log(orig.a, copy.a); // 1 10
- // Задача 6. Перебор с фильтром
- let book = { title: 'JS Guide', author: 'Author', year: 2020, pages: 300 };
- for (let key in book) {
- if (typeof book[key] === 'string') {
- console.log(key, book[key]);
- }
- }
- // title JS Guide
- // author Author
- // Задача 7. Обратный ключ–значение
- let map = { a: 1, b: 2, c: 3 };
- let inv = {};
- for (let key in map) {
- inv[map[key]] = key;
- }
- console.log(inv); // { '1':'a', '2':'b', '3':'c' }
- // Задача 8. Метод в объекте
- let rectangle = {
- width: 10,
- height: 5,
- area: function() {
- return this.width * this.height;
- }
- };
- console.log(rectangle.area()); // 50
- // Задача 9. Глубокое копирование
- let settings = { volume: 10, options: { theme: 'dark' } };
- let copySettings = JSON.parse(JSON.stringify(settings));
- copySettings.options.theme = 'light';
- console.log(settings.options.theme, copySettings.options.theme);
- // 'dark', 'light'
- // Задача 10. Объединение объектов
- let defaults = { theme: 'light', show: true };
- let userPrefs = { theme: 'dark' };
- let config = Object.assign({}, defaults, userPrefs);
- console.log(config.theme, config.show);
- // 'dark', true
Advertisement
Add Comment
Please, Sign In to add comment