90% 前端开发者都不知道的 JavaScript 实用小技巧

面试神器之数组去重

const a = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]

操作数组担心 falsy 值?

const res = myArray.filter(Boolean).map( // todo )

生成一个真正的空对象

const o = Object.create(null)
// o.__proto__ === "undefined"
// 对象 o 不再含有任何属性

合并对象

const a = {m: 1, n: 2}
const b = {n: 3, x: 5}

cons res = {
    ...a,
    ...b
}

/*
res = {
  m: 1,
  n: 3,
  x: 5
}
*/

要求函数参数必传

const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// 这会抛出错误
hello();
hello(undefined);

// 正确姿势
hello(null);
hello('David');

解构后使用别名

const obj = { x: 1 };

// otherName 的值就是 obj.x
const { x: otherName } = obj;

快速获取 URL 参数

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

// 假设 "?post=1234&action=edit"

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 帮助我们快速有效的解析参数,如果它依然存在浏览器兼容性的问题,这里有一个 polyfill:

function getUrlParameter(name) {
    name = name.replace(/[[]/, '\[').replace(/[]]/, '\]');
    const regex = new RegExp('[\?&]' + name + '=([^&#]*)');
    const results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/+/g, ' '));
};

...

对了,你可能发现所有栗子我都使用 const 来声明变量,如果你感觉疑惑,可以看看这篇文章:【JavaScript 的内存模型】

引用

7 Useful JavaScript Tricks
Get Query String Parameters with JavaScript

原文地址:https://www.cnblogs.com/fayin/p/10811954.html