destrukturizacija

Это старая версия документа!


одночасне створення нових змінних та призначеня їм значень з іньшого обїекта

Деструктурізація обїекта

const userProfile = {
    name: 'tro',
    commq: 23,
    hass: false
}

const {name, commq, hass} = userProfile

console.log(name); // tro
console.log(commq); // 23
const book = {
  title: "The Last Kingdom",
  author: "Bernard Cornwell",
  genres: ["historical prose", "adventure"],
  isPublic: true,
  rating: 8.38,
};

// Деструктуризуємо
const { title, author, isPublic, rating } = book;

// Використовуємо
const accessType = isPublic ? "pulbic" : "private";
const message = `Book ${title} by author ${author} with rating ${rating} is in ${accessType} access!`;

З метою уникнення присвоєння undefined під час деструктуризації неіснуючих властивостей, можна задати змінним значення за замовчуванням, використовуючи знак =. Це значення буде присвоєно тільки у випадку, коли в об'єкті відсутня властивість із таким ім'ям.

const book = {
  title: "The Last Kingdom",
  author: "Bernard Cornwell",
};

// Додамо зображення обкладинки, якщо вона відсутня в об'єкті книги
const {
  title,
  author,
  coverImage = "<https://via.placeholder.com/640/480>"
} = book;

console.log(title); // "The Last Kingdom"
console.log(author); // "Bernard Cornwell"
console.log(coverImage); // "<https://via.placeholder.com/640/480>"
const book = {
  title: "The Last Kingdom",
  author: "Bernard Cornwell",
  genres: ["historical prose", "adventure"],
  isPublic: true,
  rating: 8.38,
};

// Деструктуризуємо
const { title, author: bookAuthor, isPublic, rating: bookRating } = book;
console.log(title); // "The Last Kingdom"
console.log(bookAuthor); // "Bernard Cornwell"
console.log(isPublic); // true
console.log(bookRating); // 8.38

Для цього після нового імені ставимо дорівнює = і вказуємо її значення за замовчуванням. Якщо така властивість існує в об'єкті, у змінну буде присвоєно її значення.

В іншому випадку змінній буде присвоєно значення за замовчуванням.

const book = {
  title: "The Last Kingdom",
  coverImage:
    "<https://images-na.ssl-images-amazon.com/images/I/51b5YG6Y1rL.jpg>",
};

const {
  title,
  coverImage: bookCoverImage = "<https://via.placeholder.com/640/480>",
} = book;

console.log(title); // "The Last Kingdom"
console.log(bookCoverImage); // "<https://images-na.ssl-images-amazon.com/images/I/51b5YG6Y1rL.jpg>"

Деструктурізація масива

const fruts = ['apple','banana']

const [fruts1, fruts2] = fruts

Деструктурізація при передачі у функцію

const userProfile = {
    name: 'tro',
    commq: 23,
    hass: false
}

const userInfo = ({name, commq})=>{
    if (commq>22){
        console.log('more that 22')
    }
}

userInfo(userProfile)

Деструктуризація параметрів

function doStuffWithBook(book) {
  const { title, pages, downloads, rating, isPublic } = book;
  console.log(title);
  console.log(pages);
}
function doStuffWithBook({ title, pages, downloads, rating, isPublic }) {
  console.log(title);
  console.log(pages);
}
function printUserInfo({ name, age, hobby }) {
  console.log(`Name: ${name}, Age: ${age}, Hobby: ${hobby}`);
}

printUserInfo({ 
	name: "Alice", 
	age: 25, 
	hobby: "dancing" 
}); // Name: Alice, Age: 25, Hobby: dancing
  • /sites/data/attic/destrukturizacija.1702755625.txt.gz
  • Последнее изменение: 2023/12/16 19:40
  • tro