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包含更多文章哦~项目哦~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值