if else
语句const x = 20;
let answer;
if (x > 10) {
answer = 'Love';
} else {
answer = 'Peace';
}
// 简写
const answer = x > 10 ? 'Love' : 'Peace';
switch
或对象代替 if else if
语句if(a == 1) {
console.log('Love')
}else if(a == 2) {
console.log('Peace')
}else {
console.log('Nian糕')
}
// 简写
switch(a) {
case 1:
console.log('Love')
case 2:
console.log('Peace')
default:
console.log('Nian糕')
}
// 简写
let handler = {
1: () => {
console.log('Love')
},
2: () => {
console.log('Peace')
},
default: () => {
console.log('Nian糕')
}
}
handler[a]() || handler['default']()
null
, undefined
, 0 或空值,使用短路求值来代替一个多重条件的if语句if (variable1 !== null || variable1 !== undefined || variable1 !== '' || variable !== 0) {
let variable2 = variable1;
}
// 简写
`const variable2 = variable1 || 'Love';`
let a;
let b;
let c = 3;
// 简写
let a, b, c =3;
const obj = {
a:a,
b:b
}
// 简写
const obj = {
a,
b
}
const o = {
method: function() {
return "Love";
}
}
// 简写
const o = {
method() {
return "Love";
}
}
function sayHello(name) {
console.log('Love', name);
}
setTimeout(function() {
console.log('Peace')
}, 2000)
list.forEach(function(item) {
console.log(item);
})
// 简写
sayHello = name => console.log('Love', name)
setTimeout(() => console.log('Peace'), 2000)
list.forEach(item => console.log(item))
if
语句function volume(l, w, h) {
if (w === undefined)
w = 3;
if (h === undefined)
h = 4;
return l * w * h;
}
// 简写
volume = (l, w = 3, h = 4 ) => (l * w * h);
volume(2) // 24
const welcome = 'You have logged in as ' + first + ' ' + last + '.'
// 简写
const welcome = `You have logged in as ${first} ${last}`;
for
循环for (var i = 1; i <= 10; i++) {
a[i] = a[i] + 1;
}
// 简写
let b = a.map(item => ++item)
参考资料