“Array Destructurant JS” Réponses codées

Destructuration des objets

const book = {
    title: 'Ego is the Enemy',
    author: 'Ryan Holiday',
    publisher: {
        name: 'Penguin',
        type: 'private'
    }
};

const {title: bookName =  'Ego', author, name: {publisher: { name }} = book, type: {publisher: { type }} = book } = book;
Scary Snail

JS des tableaux et des objets destructeurs

// 1) Destructure array items
const [first, second,, fourth] = [10, 20, 30, 40];

// 2) Destructure object properties
const { PI, E, SQRT2 } = Math;
Puzzled Puffin

Array Destructurant JS

// In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N, only the first N variables are assigned values. The values of the remaining variables will be undefined.

const foo = ['one', 'two'];

const [red, yellow, green, blue] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // undefined
console.log(blue);  //undefined
Ill Iguana

Destructeur du tableau dans ES6

function printFirstAndSecondElement([first, second]) {
    console.log('First element is ' + first + ', second is ' + second)
}

function printSecondAndFourthElement([, second, , fourth]) {
    console.log('Second element is ' + second + ', fourth is ' + fourth)
}

var array = [1, 2, 3, 4, 5]

printFirstAndSecondElement(array)
printSecondAndFourthElement(array)
Outrageous Ostrich

Destructeur dans ES6

let {a, b, c} = obj
Outrageous Ostrich

Destructeur dans ES6

var a = obj.a
var b = obj.b
var c = obj.c
Outrageous Ostrich

Réponses similaires à “Array Destructurant JS”

Questions similaires à “Array Destructurant JS”

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code