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>"
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
const user = {
  name: "Jacques Gluke",
  tag: "jgluke",
  stats: {
    followers: 5603,
    views: 4827,
    likes: 1308,
  },
};

const {
  name,
  tag,
  stats: { followers, views, likes },
} = user;

console.log(name); // Jacques Gluke
console.log(tag); // jgluke
console.log(followers); // 5603
console.log(views); // 4827
console.log(likes); // 1308
const userProfile = {
    name: 'tro',
    commq: 23,
    hass: false
}

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

userInfo(u
====== Деструктурізація масива ======
<code>
const fruts = ['apple','banana']

const [fruts1, fruts2] = fruts

Якщо змінних оголошено більше, ніж елементів масиву, їм буде присвоєно undefined. Щоб запобігти цьому, можна вказувати значення за замовчуванням.

const color = [200, 100, 255];
const [ red, green, blue, alfa = 0.3 ] = color;

console.log(rgba(${red}, ${green}, ${blue}, ${alfa})); // “rgba(200, 255, 100, 0.3)"

serProfile) </code>

  • /sites/data/attic/destrukturizacija.1702756171.txt.gz
  • Последнее изменение: 2023/12/16 19:49
  • tro