js小技巧

175 阅读2分钟

向下取整

>> 通过 ~~ 和 |0
15.96|0 >> 15
 
-15.96|0 >> -15

~~15.96 >> 15
 
~~-15.96 >> -15

Math.floor(-15.96) >> -16

~~true >> 1
 
~~false >> 0
 
~~"asdsadasd" >> 0
 
~~"43534" >> 43534
 
~~undefined >> 0
 
~~null >> 0

这两种方式会将小数点后面的直接砍掉,当取负数的时候会与Math.floor(-15.96)有所不同,可以通过~~再加1来向上取整.

数组去重

  var arr = [1, 2, 3, 3, 4];
  console.log(...new Set(arr))
  >> [1, 2, 3, 4]

快速过滤数组中值为 false 的值

  var myArray = [1, 0 , undefined, null, false];
  myArray.filter(Boolean);
  >> [1]

合并对象

  const page = {
    current: 1,
    pageSize: 10
  }
 
  const form = {
    name: "",
    sex: ""
  }

  const params = {...form, ...page};
  >> 使用展开运算符即可

函数参数必须

  const isRequired = () => { throw new Error('param is required'); };
 
  const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

  // 这里将抛出一个错误,因为名字时必须
  hello();
  // 这也将抛出一个错误
  hello(undefined);

  // 正常
  hello(null);
  hello('David');

获取查询参数

  function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    return r ? r[2] : null;
  }
  >> 通过正则
  // 假设地址栏中查询参数是这样 "?post=1234&action=edit"

  var urlParams = new URLSearchParams(window.location.search);

  console.log(urlParams.has('post')); // true
  console.log(urlParams.get('action')); // "edit"
  console.log(urlParams.getAll('action')); // ["edit"]
  console.log(urlParams.toString()); // "?post=1234&action=edit"
  console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
  >> 使用URLSearchParams API

void

void在JavaScript中是一个操作符,对传入的操作不执行并且返回undefined。void后面可以跟()来用,例如 void(0),看起来是不是很熟悉?没错,在HTML里阻止带href的默认点击操作时,都喜欢把href写成javascript:void(0),实际上也是依靠void操作不执行的意思。

交换变量

// 最安全且最快的办法是利用异或门(^)来进行
let a = 12;

let b = 123;

a = a ^ b;
b = a ^ b;
a = a ^ b;

a;  >> 123
b;  >> 12

// 最直观的写法是通过数组解构
[a, b] = [b, a];

生成[1,2,3, .... ,n] 的列表

Array(10).fill(true).map((x,i)=>i+1);
>> (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]