很久沒寫博客啦~此次寫一篇輕鬆的內容,JS裏的16個有趣的技巧,簡單總結自Tal Bereznitskey 的兩篇博客,代碼摘自原文。javascript
前9個來源於2013年的博客,後7個來源於2017年末的博客。java
// Boring if (success) { obj.start(); } else { obj.stop(); } // Hipster-fun var method = (success ? 'start' : 'stop'); obj[method]();
['milk', 'coffee', 'suger'].join(', '); // = 'milk, coffee, suger'
var name = myName || 'No name';
// 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
快速定位未完成的內容,由於正常狀況下代碼不會出現xxx。git
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');
var x = 1; debugger; // Code execution stops here, happy debugging x++;
利用全局變量能夠在控制檯中查詢變量信息,但要記得在正式上線發佈時刪除這些全局變量。es6
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;
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的時代仍是優雅地用``、${}模板字符串吧。github
let a = 'world', b = 'hello' [a, b] = [b, a] console.log(a) // -> hello console.log(b) // -> world
const [user, account] = await Promise.all([ fetch('/user'), fetch('/account') ])
打印對象數組
const a = 5, b = 6, c = 7 console.log({ a, b, c }) // outputs this nice object: // { // a: 5, // b: 6, // c: 7 // }
打印表格app
console.table(data [, columns]);
// 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
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] //沒錯,又是解構!
const obj = { ...oldObj } const arr = [ ...oldArr ] // 強大的解構
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 })
到此爲止!
感悟:解構(Destructuring)真的很強大~~~(ง •_•)งfetch
PS: 我的github包含更多文章哦~項目哦~this