很久没写博客啦~此次写一篇轻松的内容,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