JS奇谋诡计——16 Hacks

前言

好久没写博客啦~这次写一篇轻松的内容,JS里的16个有趣的技巧,简单总结自Tal Bereznitskey 的两篇博客,代码摘自原文。

Hacks!

前9个来源于2013年的博客,后7个来源于2017年底的博客。

条件运算符实现方法调用

1
2
3
4
5
6
7
8
9
// Boring
if (success) {
obj.start();
} else {
obj.stop();
}
// Hipster-fun
var method = (success ? ‘start’ : ‘stop’);
obj[method]();

join方法实现字符串拼接

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

或运算符 || 设置默认值

1
var name = myName || ‘No name’;

与运算符 && 代替 if 判断

1
2
3
4
5
6
7
8
9
// 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标记代替TODO标记

快速定位未完成的内容,因为正常情况下代码不会出现xxx。

Console的 Timing 计时

1
2
3
4
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’);

Debugger 设置断点

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

老式Debug手段——全局变量

利用全局变量可以在控制台中查询变量信息,但要记得在正式上线发布时删除这些全局变量。

1
2
3
4
5
6
7
8
9
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;

老式字符串模板

1
2
3
4
5
6
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的时代还是优雅地用``、${}模板字符串吧。

解构实现变量互换

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

解构简化Async/Await语句

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

Console妙用

  1. 打印对象

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

    1
    console.table(data [, columns]);

单行语句计算数组最大值、和

1
2
3
4
5
6
// 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

解构实现数组拼接

1
2
3
4
5
6
7
8
9
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] //没错,又是解构!

解构实现浅拷贝

1
2
3
const obj = { ...oldObj }
const arr = [ ...oldArr ]
// 强大的解构

使用命名变量提高解构的可读性

1
2
3
4
5
6
7
8
9
10
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)真的很强大~~~(ง •_•)ง