JS奇謀陰謀——16 Hacks

媒介

良久沒寫博客啦~此次寫一篇輕鬆的內容,JS里的16個風趣的技能,簡樸總結自Tal Bereznitskey 的兩篇博客,代碼摘自原文。

Hacks!

前9個來源於2013年的博客,后7個來源於2017歲尾的博客。

1.前提運算符完成要領挪用

// Boring
if (success) {
    obj.start();
} else {
    obj.stop();
}
// Hipster-fun
var method = (success ? 'start' : 'stop');
obj[method]();

2.join要領完成字符串拼接

['milk', 'coffee', 'suger'].join(', '); // = 'milk, coffee, suger'

3.或運算符 || 設置默認值

var name = myName || 'No name';    

4.與運算符 && 替代 if 推斷

// Boring
if (isThisAwesome) {
 alert('yes'); // it's not
}
// Awesome
isThisAwesome && alert('yes');
// Also cool for guarding your code
var aCoolFunction = undefined;
aCoolFunction && aCoolFunction(); // won't run nor crash

5.xxx標記替代TODO標記

疾速定位未完成的內容,由於一般情況下代碼不會湧現xxx。

6.Console的 Timing 計時

var a = [1,2,3,4,5,6,7,8,9,10];
console.time('testing_forward');
for (var i = 0; i < a.length; i++);
console.timeEnd('testing_forward');

7.Debugger 設置斷點

var x = 1;
debugger; // Code execution stops here, happy debugging
x++;

8.老式Debug手腕——全局變量

應用全局變量能夠在掌握台中查詢變量信息,但要記得在正式上線宣布時刪除這些全局變量。

var deeplyNestedFunction = function() {
 var private_object = {
 year: '2013'
 };
 // Globalize it for debugging:
 pub = private_object;
};
// Now from the console (Chrome dev tools, firefox tools, etc)
pub.year;

9.老式字符串模板

var firstName = 'Tal';
var screenName = 'ketacode'
// Super
var template = 'Hi, my name is {first-name} and my twitter screen name is @{screen-name}';
var txt = template.replace('{first-name}', firstName)
 .replace('{screen-name}', screenName);

個人發起在ES6的時期照樣文雅地用“、${}模板字符串吧。

10.解構完成變量交換

let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> world

11.解構簡化Async/Await語句

const [user, account] = await Promise.all([
  fetch('/user'),
  fetch('/account')
])

12.Console妙用

  1. 打印對象

    const a = 5, b = 6, c = 7
    console.log({ a, b, c })
    // outputs this nice object:
    // {
    //    a: 5,
    //    b: 6,
    //    c: 7
    // }
  2. 打印表格

    console.table(data [, columns]);

13.單行語句盤算數組最大值、和

// Find max value
const max = (arr) => Math.max(...arr); //也是應用了解構
max([123, 321, 32]) // outputs: 321
// Sum array
const sum = (arr) => arr.reduce((a, b) => (a + b), 0)
sum([1, 2, 3, 4]) // output: 10

14.解構完成數組拼接

const one = ['a', 'b', 'c']
const two = ['d', 'e', 'f']
const three = ['g', 'h', 'i']
// Old way #1
const result = one.concat(two, three)
// Old way #2
const result = [].concat(one, two, three)
// New
const result = [...one, ...two, ...three] //沒錯,又是解構!

15.解構完成淺拷貝

const obj = { ...oldObj }
const arr = [ ...oldArr ]
// 壯大的解構

16.運用定名變量進步解構的可讀性

const getStuffNotBad = (id, force, verbose) => {
  ...do stuff
}
const getStuffAwesome = ({ id, name, force, verbose }) => {
  ...do stuff
}
// Somewhere else in the codebase... WTF is true, true?
getStuffNotBad(150, true, true)
// Somewhere else in the codebase... I ❤ JS!!!
getStuffAwesome({ id: 150, force: true, verbose: true })

The last

到此為止!
感悟:解構(Destructuring)真的很壯大~~~(ง •_•)ง

PS: 個人github包括更多文章哦~項目哦~

    原文作者:SouthBean
    原文地址: https://segmentfault.com/a/1190000014907849
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞