JS奇谋诡计——16 Hacks

发布时间:2019-08-10 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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包含更多文章哦~项目哦~

脚本宝典总结

以上是脚本宝典为你收集整理的JS奇谋诡计——16 Hacks全部内容,希望文章能够帮你解决JS奇谋诡计——16 Hacks所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。