Javscript destructuring(分割)
なんで必要なの?
const student = {
name: 'John Doe',
age: 16,
scores: {
maths: 74,
english: 63,
science: 85
}
};
function displaySummary(student) {
console.log('Hello, ' + student.name);
console.log('Your Maths score is ' + (student.scores.maths || 0));
console.log('Your English score is ' + (student.scores.english || 0));
console.log('Your Science score is ' + (student.scores.science || 0));
}
displaySummary(student);
// Hello, John Doe
// Your Maths score is 74
// Your English score is 63
// Your Science score is 85
処理を読んで行く中で、余計な事を意識しなくてはいないのは良しとしないらしい。
# これはよくないらしい。
確かに、studentのscoresのmathsだ! となってしまうので、コード量が多くなった時に、よくないのかな
student.scores.maths
Destructinhとは
function displaySummary({ name, scores: { maths = 0, english = 0, science = 0 } }) {
console.log('Hello, ' + name);
console.log('Your Maths score is ' + maths);
console.log('Your English score is ' + english);
console.log('Your Science score is ' + science);
}
# mathsなどと目的のモノだけを呼べている
いろんな使い方があるらしい
デフォルトの設定
const person = {
name: 'John Doe',
country: 'Canada'
};
// Assign default value of 25 to age if undefined
const { name, country, age = 25 } = person;
// Here I am using ES6 template literals
console.log(`I am ${name} from ${country} and I am ${age} years old.`);
// I am John Doe from Canada and I am 25 years old.'
使った事ないな
違う変数名をつけられる
const person = {
name: 'John Doe',
country: 'Canada'
};
// Assign default value of 25 to years if age key is undefined
const { name: fullname, country: place, age: years = 25 } = person;
// Here I am using ES6 template literals
console.log(`I am ${fullname} from ${place} and I am ${years} years old.`);
// I am John Doe from Canada and I am 25 years old.'
どんなメリットがあるんだろう
ネストにも対応できる
const student = {
name: 'John Doe',
age: 16,
scores: {
maths: 74,
english: 63
}
};
// We define 3 local variables: name, maths, science
const { name, scores: {maths, science = 50} } = student;
console.log(`${name} scored ${maths} in Maths and ${science} in Elementary Science.`);
// John Doe scored 74 in Maths and 50 in Elementary Science.
他にもたくさん!!!
学び
初期設定は || を使うんだね
(student.scores.maths || 0)); # maths に値が入っていなかったら 0にする
英単語
caveats 注意点
この記事が気に入ったらサポートをしてみませんか?