JavaScript让前端飞JavaScript 进阶营

JavaScript 通过简写增加代码可读性

2019-02-20  本文已影响14人  Nian糕
Unsplash
const x = 20;
let answer;
if (x > 10) {
    answer = 'Love';
} else {
    answer = 'Peace';
}

// 简写
const answer = x > 10 ? 'Love' : 'Peace';
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']()
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))
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 (var i = 1; i <= 10; i++) {
    a[i] = a[i] + 1;
}

// 简写
let b = a.map(item => ++item)

参考资料
19+ JavaScript Shorthand Coding Techniques

End of File

行文过程中出现错误或不妥之处在所难免,希望大家能够给予指正,以免误导更多人,最后,如果你觉得我的文章写的还不错,希望能够点一下喜欢关注,为了我能早日成为简书优秀作者献上一发助攻吧,谢谢!^ ^

上一篇下一篇

猜你喜欢

热点阅读