Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.
JavaScript developers spend a lot of time pulling data out of objects and arrays. Like
var options = {
repeat: true,
save: false
};
// later
var localRepeat = options.repeat,
localSave = options.save;
With destructuring you will
var options = {
repeat: true,
save: false
};
var { repeat: localRepeat, save: localSave } = options;
console.log(localRepeat); // true
console.log(localSave); // false
Destructuring nested objects
var options = {
repeat: true,
save: false,
rules: {
custom: 10,
}
};
var { repeat, save, rules: { custom }} = options;
console.log(repeat); // true
console.log(save); // false
console.log(custom); // 10
Array Destructuring
var colors = [ "red", "green", "blue" ]; var [ firstColor, secondColor ] = colors; console.log(firstColor); // "red" console.log(secondColor); // "green"
No comments:
Post a Comment