一些抖机灵的js用法

260 阅读1分钟

为什么要分享

分享就一个最纯粹的原因,就是「我有一些知识,是别人不知道的,但对他人会有所帮助,所以我想分享给大家」。

分享的本意就是总结并传播知识,分享的核心是利他。

额..我总结不出来。

感觉我不配姓前了。前端最喜欢什么?前端天花板们喜欢非前端的东西。

非前端的东西。俺更写不出来了

内容不够,表情包来凑

整理了一些东西。比较轻松,安利给大家。

内容

从数组中过滤到虚值

0, undefined, null, false, "", ''这样的假值可以通过下面的技巧轻易地过滤掉。

const array = [3, 0, 6, 7, '', false];

array.filter(Boolean);

// 输出

(3) [3, 6, 7]//缺点会过滤掉0

将字符串转换为数字

const str = '123'

const num = +str //const num = str*1

console.log(typeof num) // number

flat

const arr = [1, 2, 3, [4, 5, [6, 7]]];

const flatten = arr.flat(Infinity);

console.log(flatten);

优点:会跳过空位,返回新数组,不会修改原数组

if中判断条件的吐槽,es6中includes

if(

    type == 1 ||

    type == 2 ||

    type == 3 ||

    type == 4 ||

){

   //...

}

//复制代码

const condition = [1,2,3,4];



//改进

if( condition.includes(type) ){

   //...

}

URLSearchParams 方法

// 创建一个URLSearchParams实例

const urlSearchParams = new URLSearchParams(window.location.search);

// 把键值对列表转换为一个对象

const params = Object.fromEntries(urlSearchParams.entries());

代码执行时长

使用 console.time() 和 console.timeEnd() 来标记循环耗时

console.time('Timer1');

 

var items = [];

 

for(var i = 0; i < 100000; i++){

   items.push({index: i});

}

 

console.timeEnd('Timer1');

// Timer1: 25.840087890625ms

// 会打印出从开始到结束用了多少时间

快速幂运算

从 ES7 开始,可以使用 ** 进行幂运算,比使用 Math.power(2,3) 要快得多。

console.log( 2 ** 3 )   // 8

但要注意不要把这个运算符于 ^ 混淆在一起了,^ 通常用来表示指数运算,但在 JavaScript 中,^ 表示位异或运算。在 ES7 之前,可以使用位左移运算符 << 来表示以 2 为底的幂运算:

Math.pow(2, n)

2 << (n - 1)

2 ** n

例如,2 << 3 = 16 等同于 2 ** 4 = 16。

短路求值

使用三元运算符可以很快地写出条件语句,

但有时候三元运算符仍然很复杂,我们可以使用逻辑运算符 && 和 || 来替代,让代码更简洁一些。这种技巧通常被称为“短路求值”。假设我们想要返回两个或多个选项中的一个,使用 && 可以返回第一个 false。如果所有操作数的值都是 true,将返回最后一个表达式的值。

let a = 1, b = 2, c = 3;

console.log( a && b && c )   // 3

console.log( null && 0 )   // null

使用 || 可以返回第一个 true。如果所有操作数的值都是 false,将返回最后一个表达式的值。

let a = 1, b = 2, c = 3;

console.log( a || b || c )   // 1

console.log( null || 0 )   // 0

快速打印一个5颗星

function getRating(rating) {

 if(rating > 5 || rating < 0) throw new Error('数字不在范围内'); 

   return '★★★★★☆☆☆☆☆'.substring(5 - rating, 10 - rating );

}

强制要求参数

const required = () => {

  throw new Error('Missing parameter')

};

const add = (a = required() , b = required()) => a + b; 

add(1, 2) //3

add(1) // Error: Missing parameter.

数值交换

let param1 = 1; let param2 = 2; 

//swap and assign param1 & param2 each others values 

[param1, param2] = [param2, param1];

console.log(param1) // 2

console.log(param2) // 1

more

25个你不得不知道的数组reduce高级用法